Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 287
Diego Mijelshon Avatar asked Feb 24 '23 17:02

Diego Mijelshon


2 Answers

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.
like image 106
George Birbilis Avatar answered Mar 03 '23 08:03

George Birbilis


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.

like image 28
H.B. Avatar answered Mar 03 '23 08:03

H.B.