简体   繁体   English

将复选框列添加到DataGrid

[英]Add Checkbox Column to a DataGrid

i´m trying to add a checkboxcolum in a datagrid control in WPF. 我试图在WPF的datagrid控件中添加一个checkboxcolum。

I´ve done this in Windows.Forms and it works very well. 我已经在Windows.Forms中做到了,并且效果很好。

So now i want to write my new program in WPF for the future. 因此,现在我想为将来在WPF中编写新程序。

My way that i want to do: The Data will come from a Database as a Dataset. 我想做的方式:数据将来自数据库作为数据集。

Some fields have values that i want to display as a checkbox. 有些字段具有我想显示为复选框的值。 Now i´ve set the datagrid autocreatecolumn true, the data will be displayed. 现在,我已将datagrid autocreatecolumn设置为true,将显示数据。

Now i want to delete the column that displays the value and will add a checkbox column. 现在,我想删除显示该值的列,并添加一个复选框列。

Is that possible or should i create the columns via datatemplate? 有可能吗?还是应该通过datatemplate创建列?

WPF DataGrid provides a feature called AutoGenerateColumns that automatically generates column according to the public properties of your data objects. WPF DataGrid提供了一项称为AutoGenerateColumns的功能,该功能可以根据数据对象的公共属性自动生成列。 It generates the following types of columns based on the type of the value, and you dont have to do anything.: 它根据值的类型生成以下类型的列,您无需执行任何操作。:

1. TextBox columns for string values
2. CheckBox columns for boolean values
3. ComboBox columns for enumerable values
4. Hyperlink columns for Uri values

You can subscibe to AutoGeneratingColumn event and change the column that is being generated: 您可以订阅AutoGeneratingColumn事件并更改正在生成的列:

public MyWindow(){
       myDataGrid.AutoGeneratingColumn += AutoGeneratingColumnHandler;
}

private void AutoGeneratingColumnHandler(object sender, DataGridAutoGeneratingColumnEventArgs e) {
        var bindingPath = ((e.Column as DataGridBoundColumn).Binding as Binding).Path.Path;
        if (bindingPath == "MYPATH") {
              var checkBoxColumn = new DataGridCheckBoxColumn();
              checkBoxColumn.Binding = new Binding(bindingPath);
              e.Column = checkBoxColumn;
        }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM