views:

63

answers:

1

I have an application that allows the user to change color schemes based on an external xaml file. When the user clicks on a MenuItem that contains the name of a theme, the following code executes:

MenuItem mi = sender as MenuItem;
string executingDirectory = Assembly.GetExecutingAssembly().Location.Substring(0, Assembly.GetExecutingAssembly().Location.LastIndexOf("\\"));
string path = System.IO.Path.Combine(executingDirectory + "\\Themes", mi.Header.ToString() + ".xaml");

if (File.Exists(path))
{
    using (FileStream fs = new FileStream(path, FileMode.Open))
    {
        ResourceDictionary dic = (ResourceDictionary)XamlReader.Load(fs);
        Resources.MergedDictionaries.Clear();
        Resources.MergedDictionaries.Add(dic);
    }
}

This works for most of the application – all of my resource brushes change – with one exception. I have a subcontrol whose background color is determined by a value binding using a converter. Rather than hard-code the colors into the converter, though, I had the converter use string constants for brush names and then return the color from App.Current.Resources:

Brush ret = Application.Current.Resources[brushToReturn] as Brush;

What seems to be happening here is that Application.Current.Resources isn’t holding the same set of resources as the window. I have tried loading the theme into Application.Current.Resources and reading from that in the converter, but that doesn’t seem to work either. Can anyone tell me what I’m missing here? Is there a way to change, say, Application.Current.Resources and have it affect the opened windows?

Thanks!

A: 

It's hard to say without seeing all your code, but checking the Resources property does not automatically check merged dictionaries. Also, if you're merging the theme resources at the Window level then they won't be at the application level at all. For consistency sake, you're best off having your converter get a hold of the element it is converting for and using FindResource:

var frameworkElement = values[0] as FrameworkElement;
var resource = frameworkElement.FindResource("SomeKey") as Brush;

Using an IMultiValueConverter might be your best option. Alternatively, if that gets too messy, you might look into writing a markup extension that does what you need.

HTH, Kent

Kent Boogaart