combobox with checkbox within a WPF DataGrid

2019-02-21 07:12发布

I need to display combobox with checkbox option within a DataGrid in WPF. Please provide any solution for that.

I have tried the below code

<toolkit:DataGridTemplateColumn Header="Template">
                <toolkit:DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <ComboBox>
                            <ComboBoxItem BindingGroup="{Binding Program}">
                                <StackPanel Orientation="Horizontal">
                                    <CheckBox IsChecked="{Binding IsChecked}" Width="20" />
                                    <TextBlock Text="{Binding Program}" Width="100" />
                                </StackPanel>
                            </ComboBoxItem>
                        </ComboBox>
                    </DataTemplate>
                </toolkit:DataGridTemplateColumn.CellTemplate>
            </toolkit:DataGridTemplateColumn>

It will output like this

enter image description here

Anyone please help to load collection of items in combobox and to correct my code.

CS code:

  private void resultGrid_Loaded(object sender, RoutedEventArgs e)
    {
        var programs = new List<Programs>();
        programs.Add(new Programs("test", false));
        programs.Add(new Programs("test1", false));
        programs.Add(new Programs("test2", true));

        //var grid = sender as DataGrid;
        resultGrid.ItemsSource = programs;
        Combo.ItemsSource = programs;            

    }

And the Model:

  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; }
}

Finaly got an idea @Sheridan mentioned :

enter image description here

1条回答
萌系小妹纸
2楼-- · 2019-02-21 07:37

You provided a DataTemplate to define that your column should render a ComboBox, so I'm not really sure why you can't just extend that and provide a DataTemplate to define that your ComboBoxItems should render as Checkboxes. Try something like this:

<toolkit:DataGridTemplateColumn Header="Template">
    <toolkit:DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <ComboBox>
                <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>

I'll leave you to finish this off.

查看更多
登录 后发表回答