首页 > 解决方案 > 从 C# 代码添加 MergedDictionaries 字段

问题描述

XAML 变体:

<Application.Resources>
<ResourceDictionary>
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="needed line" />
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

如何使用代码添加它?(我试图根本不使用 xaml)

标签: c#.netwpf

解决方案


在 App.xaml.cs 的某个地方(例如构造函数)

var src1 = new ResourceDictionary { Source = new Uri("Dictionary1.xaml", UriKind.Relative) };
this.Resources.MergedDictionaries.Add(src1);

编辑:或者您的意思是您想要构建资源以在没有 XAML 的情况下合并?

如果是这样,请这样做

//build some resources
var btnStyle = new Style(typeof(Button));
btnStyle.Setters.Add(new Setter(Button.BackgroundProperty, Brushes.Red));

var src1 = new ResourceDictionary();
src1.Add("btnStyleKey", btnStyle);

this.Resources.MergedDictionaries.Add(src1);

推荐阅读