Trying WPF in a personal project, I wanted to be able to switch to Dark or Light mode easily.
While doing some research I discovered the use of Themes. Here is a small description on how I used it to switch from Dark to Light UI and allowing the addition of other themes.
Theme Management
Each Theme can be materialized in a Ressource Dictionary file.
Create a Folder named Themes then create Ressource Dictionary files named Dark.xaml and Light.xaml.
usingSystem.Windows;namespaceWpfApi{internalclassTheme{/// <summary>/// Change the theme of the application/// </summary>/// <param name="themeName"> name of the theme. must be consistent with the RessourceDictionary name and the entry in theme list.</param>publicstaticvoidChangeTheme(stringthemeName){ResourceDictionarytheme=newResourceDictionary(){Source=newUri($"Themes/{themeName}.xaml",UriKind.Relative)};Application.Current.Resources.Clear();Application.Current.Resources.MergedDictionaries.Add(theme);}/// <summary>/// List of available themes, must be consistent with Ressource Dictionary names in Themes folder./// </summary>privatestaticList<string>_themes=newList<string>{"Light","Dark"};publicstaticList<string>GetThemes(){return_themes;}}}
Main Window
In the main Window I will load a ComboBox with all the available Themes and I will set up the event to update the theme when the selection changes.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#regionThemeManagement// Load Theme list into the Theme comboboxprivatevoidLoadThemes(){foreach(stringthemeinTheme.GetThemes()){toolTheme.Items.Add(theme);}toolTheme.SelectedItem="Dark";}privatevoidThemeSelection_Changed(objectsender,SelectionChangedEventArgse){Theme.ChangeTheme((string)toolTheme.SelectedItem);}#endregion
I will call the LoadThemes after the Initialization is done.
In the Windows layout, I will add the following combo box and add reference to the ressources I have created to setup the color of the controls.