简体   繁体   中英

Add Checkbox Column to a DataGrid

i´m trying to add a checkboxcolum in a datagrid control in WPF.

I´ve done this in Windows.Forms and it works very well.

So now i want to write my new program in WPF for the future.

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.

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?

WPF DataGrid provides a feature called AutoGenerateColumns that automatically generates column according to the public properties of your data objects. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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