Managing WPF resources contained in external assemblies

15 בספטמבר 2009

tags: , ,
4 comments

Here is a small how-to solution to a very common question.

Suppose I have separated my client application to multiple projects, and each project contains his own WPF resource dictionary, how do I use it?

Bottom line, you need to merge your resource dictionary to the application main resource, let’s see how to do that.

private static void RegisterResources()

    {

        ResourceDictionary dictionary = new ResourceDictionary();

        dictionary.Source = new Uri(

            "pack://application:,,,/[ASSEMBLY NAME];Component/[SUBFOLDER IF ANY]/[DICTIONARY NAME].xaml");

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

    }

Note: the strange Uri syntax, every [] is a place holder for you to put in your specific information.

I usually use this method somewhere in my module entry point. (If using prism, the class which implement IModule is a good candidate).

Ariel

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

4 comments

  1. pavely15 בספטמבר 2009 ב 21:37

    Could you do the same in XAML?

    Reply
  2. Ariel Ben Horesh16 בספטמבר 2009 ב 3:10

    @pavely, there is a xaml syntax for it. but in this scenario, nobody is going to use thiis xaml. unless you do something ugly like forcing a xaml file to be rendered.

    this is mucj cleaner.

    if you have a simple one project application that all the UI is already there, it is much simple to do it by xaml.

    For example:




    Reply
  3. Josh17 בספטמבר 2009 ב 12:42

    Hi buddy,
    Question: you are using CL / Prism with dynamically loaded modules (each of which has its own set of resource dictionaries ) using a directory catalog – you cannot reference the assembly in the pack Uri because the Shell WPF app doesnt have a project reference to the Dll – what do you recommend doing in such a situation?

    Reply
  4. Ariel Ben Horesh17 בספטמבר 2009 ב 16:26

    Hi Josh,
    You put this registration code inside your Module Entry point (assuming your resources file are part of the module).

    It doesn't matter ( I think) how the module is getting loaded, either through directory catalog or configuration. The Shell in either case doesn't have a reference to the modules.
    In other words, my solution should work for you.

    if You wish I can upload a quick sample.

    Reply