Introduction
Recently I have worked with WPF requirements to show a Combo Box with check boxes as shown in the following image. This article shows how to do it.
Procedure
To work with a Data Grid in WPF currently I am using the WPF Toolkit available in the following link.
https://wpftoolkit.codeplex.com/wikipage?title=DataGrid
In the XAML page we need to add the Data Grid code as specified below.
- <toolkit:DataGrid Name="resultGrid" Loaded="resultGrid_Loaded" ItemsSource="{Binding Programs}" CanUserAddRows="False"
- CanUserDeleteRows="False" CanUserReorderColumns="False" Margin="7,33,7,0"
- CanUserResizeRows="False" AutoGenerateColumns="False"
- AreRowDetailsFrozen="True" IsReadOnly="False" SelectionMode="Extended"
- CanUserSortColumns="False">
- <toolkit:DataGrid.Columns>
- <toolkit:DataGridTemplateColumn Header="Template">
- <toolkit:DataGridTemplateColumn.CellTemplate>
- <DataTemplate>
- <ComboBox Loaded="ComboBox_Loaded">
- <ComboBox.ItemTemplate>
- <DataTemplate>
- <StackPanel Orientation="Horizontal">
- <CheckBox IsChecked="{Binding IsChecked}" Width="20" />
- <TextBlock Text="{Binding Program}" Width="100" />
- </StackPanel>
- </DataTemplate>
- </ComboBox.ItemTemplate>
- </ComboBox>
- </DataTemplate>
- </toolkit:DataGridTemplateColumn.CellTemplate>
- </toolkit:DataGridTemplateColumn>
- <toolkit:DataGridComboBoxColumn Header="Combo" x:Name="Combo" SelectedItemBinding="{Binding Program}"/>
- <toolkit:DataGridTextColumn Header="Program" Binding="{Binding Program}"/>
- </toolkit:DataGrid.Columns>
- </toolkit:DataGrid>
In the code above we need to add a “DataGridTemplateColumn” and inside that we can create our own controls like check box and text block.
We have added two “Load” events for Data Grid and Combo box.
- private void ComboBox_Loaded(object sender, RoutedEventArgs e)
- {
- ObservableCollection<Programs> data = new ObservableCollection<Programs>();
- data.Add(new Programs("test", false));
- data.Add(new Programs("test1", false));
- data.Add(new Programs("test2", true));
-
-
- var comboBox = sender as ComboBox;
-
-
- comboBox.ItemsSource = data;
-
-
- comboBox.SelectedIndex = 0;
- }
-
- private void resultGrid_Loaded(object sender, RoutedEventArgs e)
- {
- ObservableCollection<Programs> programs = new ObservableCollection<Programs>();
- programs.Add(new Programs("test", false));
- programs.Add(new Programs("test1", false));
- programs.Add(new Programs("test2", true));
-
-
- resultGrid.ItemsSource = programs;
-
- Combo.ItemsSource = programs;
-
- }
And we have the model class as in the following:
- public class Programs
- {
- public Programs(string Program, bool IsChecked)
- {
- this.Program = Program;
- this.IsChecked = IsChecked;
- }
- public string Program { get; set; }
- public bool IsChecked { get; set; }
- }
Finally we can embed check boxes within the combo box in the DataGrid.