Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF styles, create style page to be used across application in XAML

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

like image 459
user3428422 Avatar asked Sep 16 '25 14:09

user3428422


2 Answers

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>
like image 175
Rohit Vats Avatar answered Sep 18 '25 04:09

Rohit Vats


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.

like image 34
amnezjak Avatar answered Sep 18 '25 03:09

amnezjak