Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting or modifying ThemeResource in code

My questions is very specific to ThemeResources in a Windows 10 Store App. Unfortunately several things available in "classic" WPF are different or not available here.

What I am trying to achieve for lots of ui elements:

  • Allow the user to use the system's accent color (in XAML this would be {ThemeResource SystemAccentColor} as value.)
  • Allow the user to use a custom/fixed color instead. (I could override the SystemAccentColor key in the resourcedictionary)
  • Allow to switch between system accent and custom color at runtime (I could bind against a color instead of using a resource)

But I have not found a good solution to achieve all of this. If I have my own resource dictionary with the custom color, I won't get rid of it when the user would like to switch back to the system's accent color. And using a property I am binding against has the drawback that I do not realize if the user changes the accent color in the system settings while the app is running - using the {ThemeResource} markup it does.

Any ideas how to get this done properly? If it would be possible to set the ThemeResource from code I could write some behavior for this, but it seems not to be available.

like image 830
Donny Rolando Avatar asked Oct 26 '15 21:10

Donny Rolando


1 Answers

There is a way how to kinda set ThemeResource in code... I've tested it only on W10 Creators Update so it may not work on older versions, but you can create your own resource that is referencing the original ThemeResource you want to use and then use this resource:

XAML:

<SolidColorBrush x:Key="MyBorderBrush" Color="{ThemeResource SystemAccentColor}"/>

C#:

element.BorderBrush = (SolidColorBrush)Resources["MyBorderBrush"];

The border color of element will be the same as the Accent Color selected in Windows Settings and it will change even when your app is running and user changes it.

like image 72
Marian Dolinský Avatar answered Sep 21 '22 19:09

Marian Dolinský