Search code examples
wpfdata-bindingwpf-controlswpfdatagrid

Complex header styled in WPF


Is it possible to take something like this:

<DataGridTextColumn.Header>
    <StackPanel Orientation="Horizontal">
        <Label Content="BlahBlahBlah"/>
        <Expander x:Name="Blah_Filter"/>
    </StackPanel>
</DataGridTextColumn.Header>

And make it a style so I don't have to type it out for every column. I would like to name the columns individually also, if that's possible. Per usual any help is appreciated.


Solution

  • You can change the header ContentTemplate with something like

    <Window.Resources>
        <Style TargetType="{x:Type DataGridColumnHeader}"
               x:Key="ColumnHeaderTemplate">
            <Setter Property="ContentTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <Label Content="{Binding}" />
                            <Expander />
                        </StackPanel>
                    </DataTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>
    
    <DataGrid>
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding Column1Content}"
                                HeaderTemplate="{StaticResource ColumnHeaderTemplate}"
                                Header="BlahBlahBlah1" />
            <DataGridTextColumn Binding="{Binding Column2Content}"
                                HeaderTemplate="{StaticResource ColumnHeaderTemplate}"
                                Header="BlahBlahBlah2" />
        </DataGrid.Columns>
    </DataGrid>
    

    where Column1Content and Column2Content are the bindings to your cell datas and BlahBlahBlah1 and BlahBlahBlah1 are the header titles.