In order to change the themes of WPF Window dynamically, you can create several ResourceDictionary
files and place then for e.g. in the folder Themes
:
Listing 1. ResourceDictionary file (XAML)
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib">
... SAMPLE STYLES
<Style TargetType="Rectangle">
<Setter Property="Fill" Value="Green" />
</Style>
<Style TargetType="TextBox">
<Setter Property="Background" Value="Green"/>
</Style>
</ResourceDictionary>
then refer to the default theme (e.g. Blue.xaml) in the main Window XAML
Listing 2. set default theme in Window XAML
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Themes\Blue.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
and dynamically switch between the theme (for e.g. to "Green.xaml) using Window's Control
event handler (e.g. Button.Click event) in C# code behind module:
Listing 3. Dynamically set WPF Window Theme ResourceDictionary
/// <summary>
/// Dynamically set WPF Window Theme resource dictionary
/// </summary>
private void SelectGreenTheme()
{
// prefix to the relative Uri for Theme resources (xaml file)
string _prefix = String.Concat(typeof(App).Namespace, ";component/");
// clear all resource dictionaries in this window
// Note: on app level use: Application.Current.Resources.MergedDictionaries.Clear();
this.Resources.MergedDictionaries.Clear();
// add resource theme dictionary to this window
// Note: on app level use: Application.Current.Resources.MergedDictionaries.Add
this.Resources.MergedDictionaries.Add
(
new ResourceDictionary { Source = new Uri(String.Concat(_prefix + "Themes\Green.xaml, UriKind.Relative) }
);
}