Marc Melvin’s Blog

WPF

Programmatically Merging a ResourceDictionary from Another Assembly

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

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");
1 Comment more...

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...