c# - 合并资源字典

标签 c# wpf styles resourcedictionary

我正在尝试在后面的代码中合并 wpf 资源字典,但由于某些原因,这不起作用。例如,如果我尝试在文档本身上合并词典,它正在运行:

<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 并在代码中试试这个:

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

这会因为找不到资源而中断。

最佳答案

您不能使用 Source 属性从代码中加载资源字典。

来自 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."

因此,一些伪代码:

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

Here is another example如何做到这一点:

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);

关于c# - 合并资源字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2622447/

相关文章:

c# - 按公司名称过滤 Active Directory 用户,Asp.net Core 2.1

c# - 如何在一定时间后停止纹理滚动

c# - 由于 PreviewMouseLeftButtonDown,Datagrid 内的按钮未被触发

android - 如何更改 Android 5.0 的 DatePicker 对话框颜色

css - React Semantic UI 中的速记模态内容不适用于 HTML 标签

c# - 如何在 linq DataSource 中插入空记录?

c# - 通知 WPF DataGrid 更改

当列宽缩小时,WPF DataGrid 不会缩小

css - WordPress的子导航栏

c# - DataReader 已经打开