How do I style the column header on a UWP CommunityToolkit DataGrid

Viewed 2825

I'm currently looking at the UWP CommunityToolkit DataGrid. I've been through the docs, but I'm not finding them clear on how to apply a ColumnHeaderStyle. I'm not sure what I should be targeting in the column header to set my style. I'm wishing to change the background and foreground colors. I would also like these properties to apply across the whole header, not just individual columns.

 <controls:DataGrid.ColumnHeaderStyle>
       <Style TargetType="">
             <Setter Property="" Value=""/>
       </Style>                                       
 </controls:DataGrid.ColumnHeaderStyle>
3 Answers

This one had me puzzled for a while, but I eventually discovered you need to add another XML namespace declaration in order to target the column header.

<Application
    x:Class="MyApp"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls"
    xmlns:controlsprimitives="using:Microsoft.Toolkit.Uwp.UI.Controls.Primitives">

So in this case I just appended:

xmlns:controlsprimitives="using:Microsoft.Toolkit.Uwp.UI.Controls.Primitives"

Then you can create a style with this target:

<Style x:Key="ColumnHeaderStyle" TargetType="controlsprimitives:DataGridColumnHeader">
    <!-- style properties -->
</Style>

(As of writing this, however, there seems to be weird styling behavior in doing this for some reason.)

You can override DataGridColumnHeaderBackgroundBrush and DataGridColumnHeaderForegroundBrush in your App.xaml as below:

<SolidColorBrush x:Key="DataGridColumnHeaderBackgroundBrush" Color="#FFCB2128" />
<SolidColorBrush x:Key="DataGridColumnHeaderForegroundBrush" Color="#FFB03060" />

The answer from @user1559112 got me on the right track, but it took some time to realize that in order to deal with the "weird styling behavior", it wasn't enough to just add a setter for the Background. I had to override the template like this:

<controls:DataGrid.ColumnHeaderStyle>
    <Style TargetType="controlsprimitives:DataGridColumnHeader">
        <Setter Property="ContentTemplate">
            <Setter.Value>
                <DataTemplate>
                    <TextBlock Text="{Binding}" />
                </DataTemplate>
            </Setter.Value>
        </Setter>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="prms:DataGridColumnHeader">
                    <ContentPresenter Background="{ThemeResource HeaderBackgroundBrush}" />
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</controls:DataGrid.ColumnHeaderStyle>
Related