Question

I have looked across the web to see if there was a simple explanation for my problem. But a lot of answers are based around writing code behind (C#) which I don't think you need to do.

I basically want to have a style page so instead of copying and pasting the same code, I can reference that file (A bit like CSS)

Basically, I have a Datagrid Header with this style

           <DataGridTextColumn.HeaderStyle>
              <Style TargetType="{x:Type DataGridColumnHeader}">
                 <Setter Property="HorizontalContentAlignment" Value="Center" />
                 <Setter Property="Foreground" Value="White"/>
                 <Setter Property="FontWeight" Value="Bold"/>
                 <Setter Property="Background" Value="LightBlue" />
              </Style>
           </DataGridTextColumn.HeaderStyle>

But at the moment I am copying and pasting this for every single DataGrid header in my app. Surely there is an easy way to stop this duplication?

Thanks

Was it helpful?

Solution

Define the style under App.Resources in your App.xaml file if you want it to be applied across all DataGridColumnHeaders

<App.Resources>
   <Style TargetType="{x:Type DataGridColumnHeader}">
      ....
   </Style>
</App.Resources>

OTHER TIPS

Basically you are looking for ResourceDictionary file. It allows to share the same styles, templates, etc. across application. To 'include' resources from ResourceDictionary in your eg. Window.Resources, you must add ResourceDictionary.MergedDictionaries section like this:

<ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="pack://application:,,,/MyDll;component/Styles/slCommonStyles.xaml" />
    <ResourceDictionary Source="slGridBase.xaml" />        
    <ResourceDictionary Source="../Templates/slColumnTemplates.xaml" />    
</ResourceDictionary.MergedDictionaries>

The first 'include' uses a pack uri syntax. It's required if you are 'including' resources from another DLL library.

If you want this style to be applied to all of your DataGridTextColumn, add this style without x:Key in App Resources in App.xaml

<App.Resources>
   <Style TargetType="{x:Type DataGridColumnHeader}">
      <Setter Property="HorizontalContentAlignment" Value="Center" />
      <Setter Property="Foreground" Value="White"/>
      <Setter Property="FontWeight" Value="Bold"/>
       <Setter Property="Background" Value="LightBlue" />
    </Style>
</App.Resources>

OR you want this on selective Column headers, define x:key on style

<Style x:Key="MyHeaderStyle" TargetType="{x:Type DataGridColumnHeader}">
     <Setter Property="HorizontalContentAlignment" Value="Center" />
      <Setter Property="Foreground" Value="White"/>
      <Setter Property="FontWeight" Value="Bold"/>
       <Setter Property="Background" Value="LightBlue" />
    </Style>

and use this style like <DataGridTextColumn HeaderStyle="{StaticResource MyHeaderStyle}"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top