Question

I have a program wrriten in WPF (C#) where all of the elements has a style that points a static resource located in a ResourceDictionary by the name "Styles.xaml";

Since I need to have the styles customed, I use this file to change colors and fonts to elements all across the program.

The problem is, In order to see the changes I need to recompile, and to have another EXE wich is a slight differ version of the program (differ by colors). I don't want to maintain many versions of the program.

Is it possible to have a ResourceDictionary (or any other file) outside of the compiled EXE to function as css does with HTML? Meaning, is it possible to achieve the following: replacing the file in the folder where the EXE lies will be sufficient in order to change the colors?

Thank you.

Was it helpful?

Solution

You can obtain a ResourceDictionary instance from .xaml file (not necessary included in your project) by calling XamlReader.Load method and casting the resulting object afterwards. From that point it comes down to manipulating this dictionary in code behind. On application level you can call something like

Application.Current.Resources.MergedDictionaries.Clear();
Application.Current.Resources.MergedDictionaries.Add(dictionary);

where dictionary is the instance you have loaded. The same can be done for individual controls.

OTHER TIPS

Thanks to Nikita Brizhak , I have succeeded. Here is the full "HOW TO":

1) You need to add an OnStartUp method to App.xaml.cs. Here is the syntax:

protected override void OnStartup(StartupEventArgs e)

2) You have to clear all the resources.

  Application.Current.Resources.Clear();//This is if you have on your App.xaml a load of your resource. Clear it and than load another. 
//It is good to have this so you can see you style while working on the project, But on runtime to replace.
        Application.Current.Resources.MergedDictionaries.Clear();

3) you Have to load your dynamic resource

Final Code:

 protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        Application.Current.Resources.Clear();
        Application.Current.Resources.MergedDictionaries.Clear();
        StreamReader stream = new StreamReader("Styles.xaml");
        Application.Current.Resources.MergedDictionaries.Add(System.Windows.Markup.XamlReader.Load(stream.BaseStream) as ResourceDictionary);
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top