Dark Theme in WPF

In a recent Windows 10 update a toggle switch was added to allow the user to specify that they wanted “Dark” themes in apps:

I decided to add support for this to VidCoder. But no updates to WPF were made to make this easy. WPF does having theming support where it can pull in different .xaml resource files from a Themes folder, but this is all Luna/Aero/Win10 styling that is automatically applied based on your OS. After digging in the WPF source code I determined that there’s no way to hook in your own theme to this or manually alter which theme is loaded.

Furthermore, the actual dark theme setting is not exposed in a friendly manner to WPF. But we can still do it. Let’s get started.

Detecting Windows Dark Mode setting + High Contrast

The first step is finding out what theme we should be applying. To do that we need to tell what dark mode choice the user has made and detect when it’s changed. We also need to tell if the user has turned on High Contrast and detect when it’s changed.

Dark mode detection

To get the windows theme we need to poke into the registry. I used a WMI query to watch the registry for changes so we can update the app theme when they change the setting.

private const string RegistryKeyPath = @"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize";

private const string RegistryValueName = "AppsUseLightTheme";

private enum WindowsTheme
{
	Light,
	Dark
}

public void WatchTheme()
{
	var currentUser = WindowsIdentity.GetCurrent();
	string query = string.Format(
		CultureInfo.InvariantCulture,
		@"SELECT * FROM RegistryValueChangeEvent WHERE Hive = 'HKEY_USERS' AND KeyPath = '{0}\\{1}' AND ValueName = '{2}'",
		currentUser.User.Value,
		RegistryKeyPath.Replace(@"\", @"\\"),
		RegistryValueName);

	try
	{
		var watcher = new ManagementEventWatcher(query);
		watcher.EventArrived += (sender, args) =>
		{
			WindowsTheme newWindowsTheme = GetWindowsTheme();
			// React to new theme
		};

		// Start listening for events
		watcher.Start();
	}
	catch (Exception)
	{
		// This can fail on Windows 7
	}

	WindowsTheme initialTheme = GetWindowsTheme();
}

private static WindowsTheme GetWindowsTheme()
{
	using (RegistryKey key = Registry.CurrentUser.OpenSubKey(RegistryKeyPath))
	{
		object registryValueObject = key?.GetValue(RegistryValueName);
		if (registryValueObject == null)
		{
			return WindowsTheme.Light;
		}

		int registryValue = (int)registryValueObject;

		return registryValue > 0 ? WindowsTheme.Light : WindowsTheme.Dark;
	}
}

High Contrast detection

Our app will have 3 “modes”: Light, Dark and High Contrast. In High Contrast we’ll reference a limited set of system colors which will come from the user’s settings:

We’ll need to find if High Contrast is enabled and when it changes:

bool isHighContrast = SystemParameters.HighContrast;
SystemParameters.StaticPropertyChanged += (sender, args) =>
{
	if (args.PropertyName == nameof(SystemParameters.HighContrast))
	{
		bool newIsHighContrast = SystemParameters.HighContrast;
	}
};

Combining the values

We want to end up with a value from this enum:

public enum AppTheme
{
	Light,
	Dark,
	HighContrast
}

You’ll need to use logic to combine light/dark with the High Contrast bool to get the theme and react to changes. I used ReactiveX Observables but you might have something else. Anyhow, if High Contrast is enabled, use that theme. Otherwise, use the Light/Dark as indicated by the registry key setting.

Setting up theme swapping

After we know what theme we want, we now need to apply it. Fortunately WPF has an excellent mechanism to swap out styles: ResourceDictionaries. Make your dictionaries like so:

Then inside each:

<ResourceDictionary
	xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
	xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
	<SolidColorBrush x:Key="MyBackgroundBrush" Color="#8EC2FA" />
</ResourceDictionary>

We can specify the “default” style by including Light.xaml in App.xaml:

<Application.Resources>
	<ResourceDictionary>
		<ResourceDictionary.MergedDictionaries>
			<ResourceDictionary Source="/Themes/Light.xaml" />
		</ResourceDictionary.MergedDictionaries>

		<!-- Other App-level items -->

That will make the designer happy. Though obviously we don’t want to have that theme all the time. We can swap out the theme before opening any windows in App.xaml.cs:

this.Resources.MergedDictionaries[0].Source =
    new Uri($"/Themes/{appTheme}.xaml", UriKind.Relative);

That way the app loads up with the correct theme. You can also run this code when the user updates the theme.

Populating the theme dictionaries

The only thing you want to put into the theme dictionaries are Brush resources (and maybe Colors if you need them). Dark and Light should have whatever looks good to you. For High Contrast, we should pick from the official SystemColors. For example, if you had a special window background brush, you’d want to define it as this in HighContrast.xaml:

<SolidColorBrush x:Key="MyBackgroundBrush" Color="{x:Static SystemColors.WindowColor}" />

If you choose from SystemColors, it will work for any High Contrast variant the user chooses, even if they customize it.

Another trick you can use in Dark.xaml is overriding system colors with your own:

<SolidColorBrush x:Key="{x:Static SystemColors.WindowBrushKey}" Color="Black" />
<SolidColorBrush x:Key="{x:Static SystemColors.WindowTextBrushKey}" Color="White" />

This causes any standard control that uses the system colors to use the one you’ve supplied.

Referencing theme colors

Now to use a theme color you should always refer to it like so:

{DynamicResource MyBackgroundBrush}

A StaticResource never changes, but a DynamicResource reference can update, which comes in handy when the users switches on/off dark mode or High Contrast.

Theming built-in controls

While the SystemColor overrides I mentioned earlier can help a lot with re-theming built-in controls, unfortunately there are a lot of controls that don’t pay any attention to system colors.

Button, for example is one of them. Unfortunately, there doesn’t appear to be any way to override these colors. The only way to re-skin them is to make a copy of their ControlTemplate and insert references to our own themed colors. Unfortunately that means that the controls will now look the same no matter what version of Windows the user has, but I don’t know of any way around it. I based mine off the styling in Windows 10, just so it would look consistent in the latest version and stay “current” longer.

Anyway, there’s a couple ways to do it: One by copying the Styles and Templates documentation for the control you want to theme. Another is by right clicking on the control in the designer, then Edit Template -> Edit a Copy.

You’ll want to park the style with ControlTemplate override in App.xaml (Or another dictionary referenced by App.xaml):

<Style x:Key="ButtonBaseStyle" TargetType="Button">
	<Setter Property="Background" Value="{DynamicResource Button.Static.Background}" />
	<Setter Property="BorderBrush" Value="{DynamicResource Button.Static.Border}" />
	<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" />
	<Setter Property="BorderThickness" Value="1" />
	<Setter Property="HorizontalContentAlignment" Value="Center" />
	<Setter Property="VerticalContentAlignment" Value="Center" />
	<Setter Property="Padding" Value="1" />
	<Setter Property="Template">
		<Setter.Value>
			<ControlTemplate TargetType="{x:Type Button}">
				<Border
					x:Name="border"
					Background="{TemplateBinding Background}"
					BorderBrush="{TemplateBinding BorderBrush}"
					BorderThickness="{TemplateBinding BorderThickness}"
					SnapsToDevicePixels="true">
					<ContentPresenter
						x:Name="contentPresenter"
						Margin="{TemplateBinding Padding}"
						HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
						VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
						Focusable="False"
						RecognizesAccessKey="True"
						SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
				</Border>
				<ControlTemplate.Triggers>
					<Trigger Property="IsDefaulted" Value="true">
						<Setter TargetName="border" Property="BorderBrush" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}" />
					</Trigger>
					<Trigger Property="IsMouseOver" Value="true">
						<Setter TargetName="border" Property="Background" Value="{DynamicResource Button.MouseOver.Background}" />
						<Setter TargetName="border" Property="BorderBrush" Value="{DynamicResource Button.MouseOver.Border}" />
					</Trigger>
					<Trigger Property="IsPressed" Value="true">
						<Setter TargetName="border" Property="Background" Value="{DynamicResource Button.Pressed.Background}" />
						<Setter TargetName="border" Property="BorderBrush" Value="{DynamicResource Button.Pressed.Border}" />
					</Trigger>
					<Trigger Property="IsEnabled" Value="false">
						<Setter TargetName="border" Property="Background" Value="{DynamicResource Button.Disabled.Background}" />
						<Setter TargetName="border" Property="BorderBrush" Value="{DynamicResource Button.Disabled.Border}" />
						<Setter TargetName="contentPresenter" Property="TextElement.Foreground" Value="{DynamicResource Button.Disabled.Foreground}" />
					</Trigger>
				</ControlTemplate.Triggers>
			</ControlTemplate>
		</Setter.Value>
	</Setter>
</Style>
<Style BasedOn="{StaticResource ButtonBaseStyle}" TargetType="Button" />

I ripped out the FocusVisualStyle override since the default one seems to work fine for all themes. I also include both a “Base” style and an implicit style (that has no key). Controls that don’t specify a style will pick up the implicit style, while control that do need to specify a style can base it on the Base style.

I also moved all the “Brush” resources out to the Theme dictionaries where they belong, and changed all the references to {DynamicResource}.

One thing to watch out for is that some overrides like ComboBox will reference a control from PresentationFramework.Aero2 in their ControlTemplate. If you see a namespace brought in that references Aero2, that means your program won’t work on Windows 7. To keep it compatible, delete the “2” to reference PresentationFramework.Aero.

There’s a lot more “grunt work” involved in picking all the colors, but that covers the overall strategy I used to convert all the app UI. Here’s our new, themed UI:

Window title bar

Now that we’ve converted all of our UI, we might see something like this:

All of the content is themed, but the title bar isn’t. It doesn’t look the best. We can fix it, but unfortunately the only way to do that is to implement the title bar from scratch all on our own. That is a whole separate journey that I go over in another post.

Here’s what we get with our custom title bar:

A pain to implement, but at least now it looks less like garbage.

Source reference

You can check out VidCoder’s source code for reference (beta branch).

5 Replies to “Dark Theme in WPF”

  1. FYI you probably want to wrap that OpenSubKey in a using block so that it gets cleaned up in a timely manner.

  2. Thanks a bunch for the code, it works like a charm for detecting the new light theme introduced with Win10 1903 when you use it on the “SystemUsesLightTheme” reg key.

Leave a Reply

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