Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the SystemColors of a DataGrid app wide

I know how to change a SystemColor for a specific UIElement like this

<DataGrid>
  <DataGrid.Resources>
    <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="LightGray" />
  </DataGrid.Resources>
</DataGrid>

But I want to make this setting for all DataGrids in my app. How can I set this up in my app.xaml file to make it work? This obviously does not work:

<Style TargetType="{x:Type DataGrid}">
  <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="LightGray" />
</Style>
like image 281
juergen d Avatar asked Dec 05 '25 20:12

juergen d


2 Answers

There a few steps you need to make before this will work.

1. Create a resource dictionary

Following the Microsoft documentation you need to create a resource dictionary and fill it with your desired elements. Something like so:

<ResourceDictionary x:Key="whatever">
    <Style TargetType="DataGrid">
        <Setter Property="Background" Value="Aqua" />
    </Style>
</ResourceDictionary>

Save this in a separate XAML file, maybe DataGridStyles.xaml.

2. Include the ResourceDictionary in your application

Now we need to include the ResourceDictionary in our application. I'll do this using merged resource dictionaries. This can be done on multiple different levels. If you want it to be global do this in App.xaml

<Application.Resources>
     <ResourceDictionary>
         <ResourceDictionary.MergedDictionaries>
             <ResourceDictionary Source="DataGridStyles.xaml" />
             <!-- Include any amount of Resource Dictionaries you want -->
         </ResourceDictionary.MergedDictionaries>
     </ResourceDictionary>
</Application.Resources>

You may have to fiddle around with the Source property of the <ResourceDictionary ... /> tags to get it to reference the correct XAML file and to get it to also include it when releasing. Personally I recommend using pack URIs

When you did this correctly, the style should properly be imported into everything that runs from App.xaml. This approach also offers other benefits, like being able to organise your styles and have them centralised instead of spread out through the app. Furthermore this approach can also allow you to switch out your styles at runtime with minimal code changes.

like image 77
MindSwipe Avatar answered Dec 08 '25 09:12

MindSwipe


Put it in the resources of the Style:

<Style TargetType="DataGrid">
    <Style.Resources>
        <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="LightGray" />
    </Style.Resources>
</Style>
like image 44
Rekshino Avatar answered Dec 08 '25 10:12

Rekshino