0
votes

OK, here's my issue:

I'm trying to apply some styles (colors) to my existing controls, e.g. set the Foreground of a Button.

To achieve this, I'm using "Static Resources", e.g. Foreground="{StaticResource PhoneSubtleBrush}". So, no matter what the Theme is (Dark or Light) the correct colours is being chosen.

Now, what if I want to define a custom style, not already included in the Static Resources? What if - let's say - I want a specific Button to appear with a Red background (on Dark mode) and with a Blue background (on Light mode) ?

How can I do that?

2

2 Answers

1
votes

If I understand your question correctly you would like to change the Background color of a Button when the Theme changes. If so, you need to reference your resource as a DynamicResource rather than a StaticResource.

You can do this by declaring the same named resource in each of you Dark and Light resource files such as this in the dark resources:

<SolidColorBrush x:Key="ButtonBackgroundColor" Color="DodgerBlue"/>

and this in the Light resources:

<SolidColorBrush x:Key="ButtonBackgroundColor" Color="SkyBlue"/>

Then in your Button set the Background to:

<Button Background="{DynamicResource ButtonBackgroundColor}"/>

That way when you change theme it will pick up the new ButtonBackgroundColor from the resource file associated with the new Theme.

0
votes

For your button you may use something like this:

Button.Background = new SolidColorBrush((Visibility)Application.Current.Resources["PhoneDarkThemeVisibility"] == Visibility.Visible ? Colors.Red : Colors.Blue);

Also you can create two identical buttons corresponding to your criteria for a light and dark theme to bind their visibility to a static resource PhoneDarkThemeVisibility so that if the active dark theme, you would see a dark button for dark theme for the light. See this article. This is "Only-XAML" solution.

You can also create two ResourceDictionaries defining colors as StaticResource (say MyAccentColor) for dark and light theme and depending on the current theme to use a one or another dictionary. See this article.