Ian
Ian

Reputation: 105

How to add Checkbox to Datagrid header dynamically with C# instead of XAML?

 private void gridView_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
    {
        if (e.PropertyName == "code" && rdbCode.IsChecked == true)
        {
            e.Column.Header = "Acct Code";
        }
        else if (e.PropertyName == "code" && rdbPart.IsChecked == true)
        {
            e.Column.MaxWidth = 0;
        }

        if (e.PropertyName == "um")
        {
            e.Column.MaxWidth = 0;
        }

        if (e.PropertyName == "part" && rdbPart.IsChecked == true)
        {
            e.Column.Header = "Part ID";
        }
        else if (e.PropertyName == "part" && rdbCode.IsChecked == true)
        {
            e.Column.MaxWidth = 0;
        }
    }

I know that I can add a checkbox to a Datagrid header with XAML, but can I add one with C# during the AutoGeneratingColumn event? I use the same Datagrid for different searches and populate the grid dynamically with different lists. I need to be able to add the "check all" checkbox to the header when the data is added, instead of being already formatted.

Upvotes: 0

Views: 380

Answers (1)

Netstep
Netstep

Reputation: 522

Probably it can be done like this:

private void DataGrid_OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    if (e.PropertyName == "Name")
    {
        e.Column.Header = new CheckBox { Content = "Check all" };
    }
}

The result:

The result

In general, all that we can do in xaml, also can be done in code

Upvotes: 3

Related Questions