Search code examples
c#wpfxamlwpfdatagrid

Change the background color of a single DataGrid column header


I'm using a WPF DataGrid and I want to change a single column header background color, without affecting the others.

I found the following question:

How to change column header's background color when using WPF datagrid,

but this will change all column headers, and I only want to change one.


Solution

  • When you use something like that:

    <DataGrid>
      <DataGrid.Resources>
        <Style TargetType="{x:Type DataGridColumnHeader}">
          <Setter Property="Background" Value="Blue" />
        </Style>
      </DataGrid.Resources>
    </DataGrid>
    

    you're changing the DataGridColumnHeader Style for ALL the ColumnHeaders in that scope, because the Style has not been given a Key.

    Now, pretend that the ItemsSource of the DataGrid is a List<C>, where C is a class with string properties called A and B. This is what you can do to set only the Style of column A:

    <DataGrid>
      <DataGrid.Resources>
        <Style TargetType="{x:Type DataGridColumnHeader}"
               Key="SpecialHeaderStyle"> <!-- here I set the Style's Key -->
          <Setter Property="Background" Value="Blue" />
        </Style>
      </DataGrid.Resources>
      <DataGrid.Columns>
        <!-- for this column I set the HeaderStyle property -->
        <DataGridTextColumn Binding="{Binding A}"
                            Header="A"
                            HeaderStyle="{StaticResource SpecialHeaderStyle}"/>
        <!-- for this column I don't -->
        <DataGridTextColumn Binding="{Binding B}"
                            Header="B"/>
      </DataGrid.Columns>
    </DataGrid>
    

    You'll the special Style set only on Column A.

    Just as an aside, give attention to this: if you change the Style in this way, you're setting a fixed background color that is not changing if you pass over with the Mouse. In order to make a more responsive header UI, you have to override its whole Template. Read this for a wider discussion.