anjulis
anjulis

Reputation: 229

Change autogenerated column type in WPF datagrid

The underlying data has type Char and values "Y","N". How can I make the grid show checkbox column while preserving binding? I tried

private void grdScenarioList_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
    {
        if (e.PropertyType == typeof(System.Char))
        {
            // Create a new column.
            DataGridCheckBoxColumn column = new DataGridCheckBoxColumn();
            column.Header = e.Column.Header;
            //column.Binding = (e.Column as DataGridCheckBoxColumn).Binding; 

            // Replace the auto-generated column with the templateColumn.
            e.Column = column;
        }

It shows checkbox column but binding is lost. If I uncomment column.binding line I get an error saying that (e.Column as DataGridCheckBoxColumn).Binding is null. Is there a way? I have a CharToBooleanConverter class that I use for checkboxes in other places but I am not sure how to assign it here.

Upvotes: 2

Views: 1278

Answers (1)

anjulis
anjulis

Reputation: 229

Found the solution

if (e.PropertyType == typeof(System.Char))
        {
            DataGridCheckBoxColumn col = new DataGridCheckBoxColumn();
            col.Header = e.Column.Header;
            Binding binding = new Binding(e.PropertyName);
            binding.Converter = new CharToBooleanConverter();
            col.Binding = binding;
            e.Column = col;
        }

Upvotes: 2

Related Questions