按名称访问的ResourceDictionary [英] Access ResourceDictionary by name
问题描述
可以说,我有我的一些Application.xaml ResourceDictionary中的定义是这样:
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)
但是,这似乎并不如此,这是错误的做法来处理的ResourceDictionary?我会很喜欢动态加载资源,MEF的能力,这似乎是一个绊脚石给我。
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.
修改
固定示例代码显示词典实际上在MergedDictionaries
Fixed example code to show the dictionaries are actually in the MergedDictionaries
推荐答案
既然你无法定义的关键,也不是一个名字对于这样的资源,这里就是你需要做什么:
Since you cannot define a key nor a name for such resource, here's what you need to do:
请你的字典的资源:
加载你的字典,保持对它的引用它做任何你用它做
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);
(从文档的合并资源字典)
这正是复制了原行为,但现在你可以查阅字典。
This exactly replicates the original behavior but now you can access the dictionary.
有关设计时,你肯定会想有在XAML中声明的字典,你可以在运行做什么那么的默认行为 - 时间是删除所有的词典,用上述方法重新加载它们。
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.
这篇关于按名称访问的ResourceDictionary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!