Search code examples
c#wpfresourcedictionary

Choosing one of multiple resource dictionaries in code - WPF


I have developed several WPF resource dictionaries with distinct styles for controls grouped together.

In my new project I cant decide which I like best so I would like a setting to enable the user to switch between them.

At present I define the resource dictionary in the App.xaml file as follows:

<Application.Resources> 
      <ResourceDictionary Source="/Styles/BlueStyle.xaml" />     
</Application.Resources>

Is it possible to put define this in C# code so that I can pick from a list of styles (perhaps from a dropdown box) Instead of being locked into one.

Thanks in advance


Solution

  • Will set the resource at runtime:

    Application.Current.Resources.Source = new Uri("/Styles/BlueStyle.xaml", UriKind.RelativeOrAbsolute);
    

    Or in a ComboBox_SelectionChanged (thats contains items like BlueStyleand RedStyle):

    ResourceDictionary dictionary = new ResourceDictionary();
    dictionary.Source = new Uri(@"/Styles/" + comboBox.SelectedValue.ToString() + ".xaml", UriKind.Relative);
    Application.Current.Resources.MergedDictionaries.Clear(); 
    Application.Current.Resources.MergedDictionaries.Add(dictionary);