Articles → WPF → Data Template In WPF
Data Template In WPF
Click to Enlarge
<ComboBox x:Name="DataTemplateComboBox"
ItemsSource="{Binding}" SelectedValuePath="ID" Width="100" Height="20"
ItemTemplate="{StaticResource ComboBoxDataTemplate}"> </ComboBox>
private DataTable GetTable() {
//
// Here we create a DataTable with four columns.
//
DataTable table = new DataTable();
table.Columns.Add("ID", typeof (int));
table.Columns.Add("Drug", typeof (string));
//
// Here we add five DataRows.
//
table.Rows.Add(1, "Indocin");
table.Rows.Add(2, "Enebrel");
table.Rows.Add(3, "Hydralazine");
table.Rows.Add(4, "Combivent");
table.Rows.Add(5, "Dilantin");
return table;
}
// In the load event of window bind combo box with data table.
private void Window_Loaded(object sender, RoutedEventArgs e) {
DataTable dt = GetTable();
DataTemplateComboBox.DataContext = dt;
}
<DataTemplate x:Key="ComboBoxDataTemplate">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.2*"></ColumnDefinition>
<ColumnDefinition Width="0.8*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<CheckBox Grid.Column="0" Width="20" Height="20"></CheckBox>
<TextBlock Grid.Column="1" Text="{Binding Drug}"></TextBlock>
</Grid>
</DataTemplate>