How to set the DataContext on a DataGrid Column Header

Philipp Schmid picture Philipp Schmid · Nov 24, 2009 · Viewed 9.1k times · Source

In my Silverlight 3 user control I am showing a basic DataGrid control. I need to generate the columns programmatically as follows:

Style headerStyle = (Style)Resources["ColumnHeaderStyle"];
DataGridTextColumn col = new DataGridTextColumn();
col.HeaderStyle = headerStyle;
dataGrid.Columns.Add(col);

The style is defined as follows:

<Style x:Name="ColumnStyle" x:Key="ColumnHeaderStyle" 
       TargetType="prim:DataGridColumnHeader">
    <Setter Property="ContentTemplate">
        <Setter.Value>
            <DataTemplate>
                <StackPanel Loaded="StackPanel_Loaded">
                    <TextBlock Text="{Binding Name}" />
                    <TextBlock Text="{Binding Data}" />
                </StackPanel>
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>

I want to set the data context of the header to a "header" object (with "Name" and "Data" properties which are referenced in the DataTemplate). Unfortunately, I cannot use the StackPanel_Loaded event as suggested elsewhere, because the event handler is also called when the user starts a column drag&drop operation.

What is the correct way of setting the DataContext of a DataGrid column header?

Answer

Philipp Schmid picture Philipp Schmid · Nov 24, 2009

Turns out that one can use the Header property (which is of type Object) as the DataContext for the DataTemplate (set as shown above):

Style headerStyle = (Style)Resources["ColumnHeaderStyle"];
DataGridTextColumn col = new DataGridTextColumn();
col.HeaderStyle = headerStyle;
col.Header = myHeaderDataContext; // DataContext for ColumnHeaderStyle
dataGrid.Columns.Add(col);