Merging Resources Dictionaries

﹥>﹥吖頭↗ 提交于 2019-12-07 00:51:49

问题


i'm trying merging wpf resource dictionaries on the code behind but for some reasion this isn't working. If i try merge the dictionaries on the document itself it's running for instance:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication212;assembly=WpfApplication212">

<ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="Theme.xaml"></ResourceDictionary>
</ResourceDictionary.MergedDictionaries>

<Style TargetType="{x:Type local:URComboBox}" BasedOn="{StaticResource ComboBoxStyle}">
</Style>

This is working, but if i comment the ResourceDictionary.MergedDictionaries and in code try this:

ResourceDictionary skin = new ResourceDictionary();
skin.Source = styleLocation;
ResourceDictionary skinFather = new ResourceDictionary();
skinFather.MergedDictionaries.Add(skin);
skinFather.Source = styleLocationFather;

This will break because can't find the resource.


回答1:


You can't use the Source property to load a Resource Dictionary from code.

From MSDN:

"Merged dictionaries can be added to a Resources dictionary through code. The default, initially empty ResourceDictionary that exists for any Resources property also has a default, initially empty MergedDictionaries collection property. To add a merged dictionary through code, you obtain a reference to the desired primary ResourceDictionary, get its MergedDictionaries property value, and call Add on the generic Collection that is contained in MergedDictionaries. The object you add must be a new ResourceDictionary. In code, you do not set the Source property. Instead, you must obtain a ResourceDictionary object by either creating one or loading one. One way to load an existing ResourceDictionary to call XamlReader.Load on an existing XAML file stream that has a ResourceDictionary root, then casting the XamlReader.Load return value to ResourceDictionary."

Hence, some pseudo code:

ResourceDictionary myResourceDictionary = XamlReader.Load(someXamlStreamReader);
anotherResourceDictionary.MergedDictionaries.Add(myResourceDictionary);

Here is another example of how to do it:

Uri uri = new Uri("/PageResourceFile.xaml", UriKind.Relative);
StreamResourceInfo info = Application.GetResourceStream(uri);
System.Windows.Markup.XamlReader reader = new System.Windows.Markup.XamlReader();
Page page = (Page)reader.LoadAsync(info.Stream);


来源:https://stackoverflow.com/questions/2622447/merging-resources-dictionaries

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