Search code examples
c#wpf.net-4.0datagridcolumn

Extend DataGrid ColumnHeaderStyle programmatically


I'm defining the style of DataGridColumnHeader by ResourceDictionary with a Setter there:

<Style TargetType="{x:Type DataGridColumnHeader}">
  <Setter Property="Background">
    <Setter.Value>
      <LinearGradientBrush EndPoint="0,0" StartPoint="0,1">

and so on (not really important.

Now I want to extend the style by a tooltip for the ColumnHeader. I have to set this tooltip in code because it is different for some situations.

I could do it that way:

var style = new Style(typeof(System.Windows.Controls.Primitives.DataGridColumnHeader));
style.Setters.Add(new Setter(ToolTipService.ToolTipProperty,"my tooltop"));
dgcol1.HeaderStyle = style;

But obviously all other style setters from the recource dictionary are overwritten then. How can I add my tooltip to the ColumnHeader by code? Does anyone have any idea? Thank you!


Solution

  • you can try this one

    <Style x:Key="baseStyle" TargetType="{x:Type DataGridColumnHeader}">
      <Setter Property="Background">
        <Setter.Value>
          <LinearGradientBrush EndPoint="0,0" StartPoint="0,1">
        </Setter.Value>
      </Setter Property="Background">
    </Style>
    
    <Style TargetType="{x:Type DataGridColumnHeader}" BasedOn={StaticResource baseStyle}>
    

    code behind

    var style = new Style(typeof(System.Windows.Controls.Primitives.DataGridColumnHeader));
    style.BasedOn = this.TryFindResource("baseStyle") as Style;
    style.Setters.Add(new Setter(ToolTipService.ToolTipProperty,"my tooltop"));
    dgcol1.HeaderStyle = style;
    

    hope this helps...