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).

Item change tracking in DynamicData

Since ReactiveUI’s ReactiveList<T> has recently been deprecated, I’ve been moving to DynamicData.

One feature I used from ReactiveList was item change tracking. It might look something like this:

var myList = new ReactiveList<MyClass>();
myList.ChangeTrackingEnabled = true;
myList.ItemChanged
	.Where(x => x.PropertyName == nameof(MyClass.SomeProperty))
	.Select(x => x.Sender)
	.Subscribe(myObject =>
	{
		// Do some stuff
	});

In DynamicData it goes like this:

var myList = new SourceList<MyClass>();
myList
	.Connect()
	.WhenPropertyChanged(myObject => myObject.SomeProperty)
	.Subscribe(propValue =>
	{
		MyClass myObject = propValue.Sender;
		string newValue = propValue.Value;
		// Do some stuff
	});

There is also WhenValueChanged, which just gives you the new property value as a straight IObservable:

myList
	.Connect()
	.WhenValueChanged(myObject => myObject.SomeProperty)
	.Subscribe(newValue =>
	{
		// Do some stuff
	});

The most powerful is WhenAnyPropertyChanged, which can tell you when any of the properties changed:

var myList = new SourceList<MyClass>();
myList
	.Connect()
	.WhenAnyPropertyChanged()
	.Subscribe(myObject =>
	{
		// Do stuff with myObject
	});

Or when any set of specified properties has changed:

var myList = new SourceList<MyClass>();
myList
	.Connect()
	.WhenAnyPropertyChanged(nameof(MyClass.FirstProperty), nameof(MyClass.SecondProperty))
	.Subscribe(myObject =>
	{
		// Do stuff with myObject
	});

WPF Databinding using DynamicData

My project is MVVM and I had been using ReactiveList<T> as my go-to observable collection for viewmodel properties. But ReactiveUI deprecated ReactiveList in 8.6.1. So I needed to get on to the new recommended library: DynamicData.

But there is no direct drop-in replacement you can do like ObservableCollection<T> <-> ReactiveList<T>. I grabbed the NuGet package, dropped in SourceList<T>, but that doesn’t work. SourceList<T> does not implement INotifyCollectionChanged, which is what WPF looks for when binding to ListView, GridView, ItemsControl, etc. So how do we bind to this thing? After some fruitless searches I dug through the source code unit tests and found the answer. Add this to the viewmodel class:

private readonly SourceList<string> myList = new SourceList<string>();
public IObservableCollection<string> MyListBindable { get; } = new ObservableCollectionExtended<string>();

And this to its constructor:

this.myList.Connect().Bind(this.MyListBindable).Subscribe();

It’s a two-stage affair. The SourceList<T> is where all the operations happen. Adds, clears, deletes and all that. But you don’t directly observe the source list. To do that, you need to call Connect() to get an IObservable<IChangeSet<T>> . If you follow this observable you can see everything that’s changed about the collection by looking at the change sets.

But you still need to do one more thing: get it in a format that the WPF UI can bind to, that is an object that implements INotifyCollectionChanged. ObservableCollectionExtended is DynamicData’s implementation of that. The Bind() call “slaves” it to the SourceList. Any changes made in the SourceList are now reflected in the ObservableCollectionExtended. A final call to Subscribe() activates it. Now since we’re exposing it as a property, we can bind our UI to it:

<ItemsControl
	ItemsSource="{Binding MyListBindable}"
	...

The important thing here is to remember that this property is here ONLY so the UI can bind to it. That’s why I’ve named it Bindable: so I’ll realize I’m doing something wrong if I try to modify it directly.

The ObservableCollectionExtended property also allows you to get batches to avoid update churn from making individual edits to the collection. When you call Edit() on the SourceList<T>:

this.myList.Edit(innerList =>
{
	innerList.Clear();
	foreach (string name in names)
	{
		innerList.Add(name);
	}
});

It will batch up all the changes made into one event under INotifyCollectionChanged, meaning the UI only needs to react once.