What is the column header bound to?

Sep 9, 2008 at 11:45 PM
When binding a DataGrid to a DataTable, by default, the header contains the name of the column specified in the DataTable. I'd like to display additional properties of the column in the header. I've been able to successfully template the header, but can't figure out the data binding.

Specifically, I have a DataTable with custom DataColumns that contain additional properties. My CustomDataColumn inherits from DataColumn and adds the extra properties "IsActive" and "InternalName", how do I go about binding to those values from a templated column header? Do I need to set the overall header's data source somewhere?



Sep 10, 2008 at 2:04 AM
There actually isn't any binding on the column header by default.  If you take a look at DataGridColumn::CreateDefaultColumn(), you'll find that it sets the header string from the ItemPropertyInfo.Name. 

Anyway, if you want to bind to properties on the DataGridColumn itself you can do something like this,



dg:DataGridTextColumn x:Name="FirstNameColumn"  DataFieldBinding="{Binding Path=FirstName}" >
            <CheckBox IsChecked="{Binding ElementName=FirstNameColumn, Path=IsFrozen, Mode=OneWay}" />


Sep 10, 2008 at 2:18 PM
Edited Sep 10, 2008 at 2:19 PM
Interesting. My columns are auto-generated though, and I have a style that is used for that customizes the header for every column. As a result, I won't know the name of the column.

The whole goal of this is to have metadata about the columns stored as properties of the DataColumns in my DataTable, which is why I extended the DataColumn. In my case, I'm building a small application to open an Excel spreadsheet, select options about each column and it then imports the data into a database. Each column will have options such as a checkbox indicating it should be imported, a textbox to override the column name, and a dropdown to specify the column type.

The trick is that every column is auto-generated. I can handle the AutoGeneratingColumn event and create my own column there, but I'm not sure how to go about assigning the data. I think I'd like to set the header's DataContext to the CustomDataColumn, but I'm not sure how to access that data in the event handler.

private void dataGrid_AutoGeneratingColumn(object sender, Microsoft.Windows.Controls.DataGridAutoGeneratingColumnEventArgs e)

var column = new DataGridTextColumn();
    var header = new DataGridColumnHeader();

    // header.DataContext = ???;

    column.Header = header;
    column.DataFieldBinding = new Binding(e.PropertyName) { Mode = BindingMode.OneWay };
    e.Column = column;