Switching themes in an application can be achieved by creating multiple external resource dictionaries and ensuring that styles and/or templates defined in these resource dictionaries contain identical names. The following example demonstrates how to switch “the look” of your application on the fly:
The sample walks through creating two styles for a button. Each style has the same name and same target, but the different “same named” styles are stored in two separate resource dictionaries. The application can then switch the style of the button at run time by loading and unloading respective resource dictionaries:
Setting up:
Creating a Theme with a style stored in a resource dictionary:
Creating a second theme:
To test resource switching at design time, try the following:
To get the buttons to do the switching at run-time, from the project palette double click window1.xaml.cs to open an external code editor and paste the following code inside the Window1 class:
public Window1()
{
this.InitializeComponent();
// Insert code required on object creation below this point.
this.greenThemeButton.Click += this.SwitchTheme;
this.brownThemeButton.Click += this.SwitchTheme;
}
private void SwitchTheme(object sender, EventArgs e)
string source = null;
if (sender == this.greenThemeButton)
source = "ResourceGreen.xaml";
else if (sender == this.brownThemeButton)
source = "ResourceBrown.xaml";
if (source != null)
ResourceDictionary resourceDictionary = new ResourceDictionary();
resourceDictionary.Source = new Uri(source, UriKind.Relative);
// if you want to have application level resources (rather than just window), change this.Resources to Application.Current.Resources
this.Resources.MergedDictionaries.Clear();
this.Resources.MergedDictionaries.Add(resourceDictionary);