Access ResourceDictionary by name

眉间皱痕 提交于 2020-01-02 09:09:39

问题


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


回答1:


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

Make your dictionary a resource :

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.




回答2:


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



来源:https://stackoverflow.com/questions/23102504/access-resourcedictionary-by-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!