Search code examples
wpfbindingdatagridstyles

Adding Header Style to DataGrid overrides (hides) data using Binding on header


I need to Style the WPF dataGrid headers AND bind the header data.

Binding works OK using:

<TextBlock Text="{Binding DataContext.HeadData, 
        RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" />

If I now add a header style to the DataGrid, the TextBlock in the style overrides the binding data.

I'm using all the latest Dot-Net and VS 2019.

Any idea how to marry the two requirements? It's consumed me!

Rich


Solution

  • Ok, I've tried it myself and this is the solution I've found:

    You have to define the TextBlock inside the Style definition

    <Style x:Key="MyHeaderStyle" TargetType="{x:Type DataGridColumnHeader}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type DataGridColumnHeader}">
                    <TextBlock Text="{Binding DataContext.HeadData, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" />
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    

    In some way, setting an Header Style, and specifying an Header content gives conflict. So you have to move everything inside the style.

    Obviously you use the Style just like this.

    <DataGridTextColumn HeaderStyle="{StaticResource MyHeaderStyle}" />
    

    Hope I've been helpful.

    EDIT

    This solution doesn't works (or else, it works for one column only DataGrid). In the comments I linked a solution given on a different question, that could be used here as well.