Observing system color changes in UWP apps

Users love personalization and expect apps to adapt to their choices. For this purpose we can use the accent color. But what if the user changes settings at runtime?

ThemeResource

XAML has a concept of ThemeResource markup extension. This allows us to dynamically reference resources based on the currently selected system theme. Anytime the user changes the accent color or switches between dark and light mode, the resource is updated.

To access the current accent color, we can use the SystemAccentColor  key.

For convenience there is also a accent color-based SolidColorBrush  resource, under the not-so intuitive SystemControlHighlightAccentBrush key.

Observing changes

Although using ThemeResource  will be sufficient for most cases, sometimes we need to be notified about color changes outside of XAML. In such cases the UISettings class comes in handy.

In stark contrast to most other similar Windows Runtime APIs, the UISettings  do not provide a Current  singleton instance property nor a GetForCurrentView  factory method, but just have a simple constructor.

Apart from many properties that let us query various UI related information ( CaretBlinkRate , CursorSize  or even HandPreference ) it also has two useful events: TextScaleFactorChanged  and ColorValuesChanged . Whereas the former event deals with text scaling, the latter event is fired whenever the system color settings are changed.

In the event handler we can check the accent color either by directly looking up the Resources  dictionary or by the GetColorValue  method:

Accessing the light/dark mode setting is a little less intuitive. We must query the UIColorType.Background  color and check if it is black or white:

Warning: the event is not always reliable. While it usually fires several times for each accent color change, sometimes the event doesn’t fire at all. I am afraid this is a bug and there is not much we can do about it.

Example code

I have prepared a sample project that demonstrates the use of UISettings.ColorValuesChanged  event including accent color and light/dark mode. The solution is available on my GitHub.

One Reply to “Observing system color changes in UWP apps”

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

*