Diego Mijelshon
Diego Mijelshon

Reputation: 52745

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)?

Upvotes: 4

Views: 10958

Answers (2)

George Birbilis
George Birbilis

Reputation: 2940

BTW, one can also manually load a ResourceDictionary as it seems:

ResourceDictionary dict = new ResourceDictionary(); 
System.Windows.Application.LoadComponent(dict, 
  new System.Uri("/SomeAssembly;component/SomeResourceDictionary.xaml",
  System.UriKind.Relative));

After that, can talk to that dict object using foreach on the Keys property it has etc

At http://msdn.microsoft.com/en-us/library/ms596995(v=vs.95).aspx says

The XAML file that is loaded can be either an application definition file (App.xaml, for example) >or a page file (MainPage.xaml, for example). The XAML file can be in one of the following locations:

  • Included in the application package.
  • Embedded in the application assembly.
  • Embedded within a library assembly at the site of origin.

Upvotes: 8

brunnerh
brunnerh

Reputation: 185445

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.

Upvotes: 1

Related Questions