Search code examples
c#wpfxamlresourcedictionary

Loading ResourceDictionary dynamically


I have a folder in my project, Templates, full of (compiled) XAML ResourceDictionaries.

In a UserControl, I want to load all the templates into the ResourceDictionary. I would use code like the following:

public MyView()
{
    InitializeComponent();
    foreach (var resourceUri in new GetResourceUrisFromTemplatesFolder())
        Resources.MergedDictionaries.Add(
            new ResourceDictionary
                { Source = new Uri(resourceUri, UriKind.Relative) });
}

What I need to write is the GetResourceUrisFromTemplatesFolder method. I need it to discover all the resources from that folder.

The URIs could take a form like /MyAssembly;component/MyNS/Templates/Template12345.xaml or ../../Templates/Template12345.xaml

Is this possible?

Do I have to manually convert the names from the assembly's compiled resources (MyAssembly.g.resources)?


Solution

  • Do I have to manually convert the names from the assembly's compiled resources (MyAssembly.g.resources)?

    That might be the case and i myself would approach it that way, however the question about how to do just that has been answered already so it should be not that much of an issue. Make sure that the dictionaries' compile action matches, and you probably want to prefix the names with a pack uri.