views:

431

answers:

1

I have a set of styles and brushes defined in a ResourceDictionary that I am loading as a MergedDictionary in XAML of my top-level control:

<ResourceDictionary.MergedDictionaries>
     <ResourceDictionary Source="/MyAssembly;component/Styles.xaml"/>
</ResourceDictionary.MergedDictionaries>

I am trying to optionally replace some of these styles & brushes if a different XAML file exists in the XAP with its own ResourceDictionary. I am trying to merge in this dictionary at runtime before InitializeComponent() is called on my user control. I am using the following code to attempt to do this:

public static class StyleLoader
{
 public static void MergeStyle(string xamlUri)
 {
  try
  {
   XDocument xaml = XDocument.Load(xamlUri);
   ResourceDictionary rd = XamlReader.Load(xaml.ToString()) as ResourceDictionary;
   Application.Current.Resources.MergedDictionaries.Add(rd);

  }
  catch (XmlException ex)
  {
   // if the file doesn't exist, we can't add it
  }
 }
}

The resource dictionary from the optional file is loaded fine and merged, however my original set of styles always seems to be overriding this. If I comment out the merged dictionary in XAML and simply load them at runtime in order it works perfectly:

    StyleLoader.MergeStyle("/MyAssembly;component/Styles.xaml");
    StyleLoader.MergeStyle("BrushReplacements.xaml");

    InitializeComponent();

My problem with this solution is that without the default styles in XAML, I can not open the project in Blend. Anyone have any ideas for a solution that will keep my default styles known to Blend but allow me to optionally override them at runtime with a dynamically loaded resource dictionary? Thanks!

A: 

Here is a solution where colors/brushes are applied with bindings instead of referring directly to the static resources:
http://blogs.msdn.com/corrinab/archive/2009/11/24/9927729.aspx
Part two:
http://blogs.msdn.com/corrinab/archive/2009/12/02/9931283.aspx

Currently I think something like this is the best way of dealing with dynamically switching themes at runtime. But it does require a lot of work to port an existing application to use a mechanism like this.

Henrik Söderlund
This is not really the way I wanted to do it (this really seems like it should be solved with resources instead of binding brushes)... but it seems like the best workaround approach to dynamic styles that I have seen to date so I will mark it as answered.
Dan Auclair