I’d like to add several resources to a ResourceDictionary from within one single line of XAML. I’ll try to make an example out of it.
Imagine this:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:util="clr-namespace:Util">
<util:MyResourceDictionaryA x:Key="MyResourceDictionaryA" />
<util:MyResourceDictionaryB x:Key="MyResourceDictionaryB" />
<util:MyResourceDictionaryC x:Key="MyResourceDictionaryC" />
<util:MyResourceDictionaryD x:Key="MyResourceDictionaryD" />
</ResourceDictionary>
I’d like to have something like:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:util="clr-namespace:Util">
<util:AllDictionaries x:Key="AllDictionaries" BaseName="MyResourceDictionary" />
</ResourceDictionary>
I’ve tried making a new ResourceDictionary like this:
public class AllDictionaries : ResourceDictionary
{
public string BaseName { get; set; }
public AllDictionaries ()
{
Clear();
var s = BaseName;
var DictionariesToLoad = new[] { "A", "B", "C", "D" };
foreach (var b in DictionariesToLoad )
{
var t = Type.GetType(b + s);
var resDir = Activator.CreateInstance(t) as ResourceDictionary;
Add(b + s, resDir);
}
}
}
However the constructor never gets called (or, not before something else in XAML references {StaticResource MyResourceDictionaryX} which hasn’t been added to the application resources so it throws an exception). I also tried putting the code on the BaseName setter, to no avail.
This is an oversimplication of what I need, but I’m just trying to make the XAML more generic.
Any hints on how could one achieve this?
Note 1: the generated resource dictionaries need to be available (using their Key) resources for the rest of the XAML in the scope where I have created the AllDictionaries resource.
Note 2: for practical purposes, let’s say I don’t have access to MyResourceDictionaryX classes source code so I can’t change anything on those
Merged Resource Dictionaryalready does what you want… it can be created through XAML or code.