Access ResourceDictionary by name

若如初见. 提交于 2019-12-06 15:24:34

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.

Yuval Itzchakov

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

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