Marc Melvin’s Blog

Programmatically Merging a ResourceDictionary from Another Assembly

by Marc Melvin on Jan.27, 2010, under WPF

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5 out of 5)
Loading ... Loading ...

I recently had to find a way to merge a ResourceDictionary that is embedded in a class library into my application’s MergedDictionaries collection, so this is how I did it. I created the following extension method:

?View Code CSHARP
    static public class ExtensionHelpers
    {
        static public void AddAssemblyResource(this Application app, string assemblyName, string path)
        {
            if (!UriParser.IsKnownScheme("pack"))
                UriParser.Register(new GenericUriParser(GenericUriParserOptions.GenericAuthority), "pack", -1);
 
            ResourceDictionary dict = new ResourceDictionary();
            Uri uri = new Uri("/" + assemblyName + ";component/" + path, UriKind.Relative);
            dict.Source = uri;
            app.Resources.MergedDictionaries.Add(dict);
        }
    }

Then, to add my resource, I simply call

?View Code CSHARP
App.Current.AddAssemblyResource("My.Assembly.Name", "Path/To/Resource.xaml");
Share and Enjoy:
  • Digg
  • del.icio.us
  • description
  • E-mail this story to a friend!
  • Facebook
  • Google
  • LinkedIn
  • Live
  • MySpace
  • Reddit
  • Slashdot
  • StumbleUpon
  • Technorati
  • TwitThis

No related posts.

1 comment for this entry:
  1. Dimitar

    Nice and clean way to abstract out the “pack” and “component” keywords when dealing with resources in WPF. Those things create suckage, but this implementation hides it from the developer.

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Archives

All entries, chronologically...