问题描述
我在尝试代码合并WPF资源字典落后,但对于一些reasion这是行不通的。如果我尝试合并它的运行实例文档本身的字典:
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>
这是工作,但如果我评论的ResourceDictionary.MergedDictionaries和代码试试这个:
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.
推荐答案
您不能使用Source属性从代码中加载资源词典。
You can't use the Source property to load a Resource Dictionary from code.
从的:
合并字典可以通过代码被添加到一个资源字典。在默认情况下,存在的任何资源属性初始为空ResourceDictionary中也有一个默认的,初始为空MergedDictionaries集合属性。要添加通过代码合并字典,你得到一个参考所需的主要ResourceDictionary中,获得其MergedDictionaries属性值,并调用添加对包含在MergedDictionaries泛型集合。您添加的对象必须是一个新的ResourceDictionary,在代码中,您没有设置源属性。相反,你必须获得通过创建一个或加载到加载现有的ResourceDictionary调用XamlReader.Load对具有的ResourceDictionary根,则铸造XamlReader.Load返回值的ResourceDictionary现有的XAML文件流之一。其中一个方式的ResourceDictionary对象。
因此,一些伪代码:
ResourceDictionary myResourceDictionary = XamlReader.Load(someXamlStreamReader);
anotherResourceDictionary.MergedDictionaries.Add(myResourceDictionary);
的如何做到这一点:
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);
这篇关于合并资源字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!