Search code examples
wpfxamldatagridwpf-style

Inherit style from control's default style


The title says it all. How do I apply a custom style on a DataGrid's column header while still inheriting the default style values for the properties that I do not override? I have already tried the method given in this SO post, but it doesn't seem to work in my case. My column header looks slightly different than the default. Here's my XAML:

<Style TargetType="DataGridColumnHeader" BasedOn="{StaticResource {x:Type DataGridColumnHeader}}">
    <Setter Property="BorderBrush" Value="Black" />
    <Setter Property="BorderThickness" Value="0,0,1,0" />
</Style>

Here's the output:

enter image description here

As you can see, the left column (this has custom style) has no padding, unlike the right column that has default style. Any clues?

(I can of course set padding in my style to get the look I want; I just need to know why didn't it inherit the padding from the default control style).

Sample code to reproduce the bug

<Window x:Class="Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
  <Grid>
    <DataGrid AutoGenerateColumns="False">
      <DataGrid.Columns>
        <DataGridTextColumn Width="100" Header="No Padding">
          <DataGridTextColumn.HeaderStyle>
            <Style TargetType="DataGridColumnHeader" BasedOn="{StaticResource {x:Type DataGridColumnHeader}}">
              <Setter Property="BorderBrush" Value="Black" />
              <Setter Property="BorderThickness" Value="0,0,1,0" />
            </Style>
          </DataGridTextColumn.HeaderStyle>
        </DataGridTextColumn>
        <DataGridTextColumn Width="100" Header="Padding" />
      </DataGrid.Columns>
    </DataGrid>
  </Grid>
</Window>

Solution

  • I used Blend to check Template of DataGridColumnHeader. I have noticed that in the Template is used DataGridHeaderBorder which derives from Border.
    http://msdn.microsoft.com/en-us/library/microsoft.windows.themes.datagridheaderborder(v=vs.110).aspx
    There is remark "If the Background or BorderBrush properties are set on the DataGrid, the rendering reverts back to the default Border implementation." and it explains your problem.
    DataGridHeaderBorder overrides OnRender method and renders header differently depending on whether the Background or BorderBrush is null or not. In one case OnRender method adds Padding and in the second case doesn't add.
    http://referencesource.microsoft.com/#PresentationFramework.Aero/DataGridHeaderBorder.cs,257