Access ResourceDictionary by name

2019-05-23 16:20发布

Lets say I have some ResourceDictionary's in my Application.xaml defined as so:

<Application>
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary x:Name="brushResources"/>
                <ResourceDictionary x:Name="graphicsResources"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

I would have assumed I could just simply access the dictionary in the code behind like so:

brushResources.MergedDictionaries.Add(someNewBrushes)
graphicsResources.MergedDictionaries.Add(someNewGraphics)

But this does not seem to be the case, is this the wrong approach to dealing with ResourceDictionary? I would really enjoy the ability to dynamically load resources with MEF, and this seems like a stumbling block to me.

EDIT

Fixed example code to show the dictionaries are actually in the MergedDictionaries

2条回答
2楼-- · 2019-05-23 16:43

You can use FrameworkElement.TryFindResource. If you are in a window code behind, do this:

var myResource = (ResourceDictionary) this.TryFindResource("someResourceName")

Returns null if the resource isn't found.

http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.tryfindresource.aspx

查看更多
ら.Afraid
3楼-- · 2019-05-23 17:03

Since you cannot define a key nor a name for such resource, here's what you need to do:

Make your dictionary a resource :

enter image description here

Load your dictionary, keep a reference to it and do whatever you have to do with it.

// Load the dictionary
ResourceDictionary resourceDictionary = null;
var resourceStream = Application.GetResourceStream(new Uri("ResourceDictionary1.xaml", UriKind.Relative));
if (resourceStream != null && resourceStream.Stream != null)
{
    using (XmlReader xmlReader = XmlReader.Create(resourceStream.Stream))
    {
        resourceDictionary = XamlReader.Load(xmlReader) as ResourceDictionary;
    }
}

Then add it to your application :

// Merge it with the app dictionnaries
App.Current.Resources.MergedDictionaries.Add(resourceDictionary);

(from the docs Merged Resource Dictionaries)

This exactly replicates the original behavior but now you can access the dictionary.

For design-time you will certainly want the default behavior of having the dictionaries declared in XAML, what you can do then at run-time is to delete all the dictionaries and reload them using the above method.

查看更多
登录 后发表回答