如何使用 C# 而不是 XAML 将两个 ResourceDictionary 对象合并到 Application.Current.Resources 中?

问题描述

这是我遇到的情况。为该示例标记的两个资源词典 Theme1 和 Theme2

public class Theme1 : ResourceDictionary
{
    protected Theme1()
    {
        Add(nameof(IconColor),"#111111");
        Add(nameof(PageBackgroundColor),"#111111");
    }
    public Color IconColor { get; }
    public Color PageBackgroundColor { get; 
}

public class Theme2 : ResourceDictionary
{
    protected Theme2()
    {
        Add(nameof(IconColorA),"#222222");
        Add(nameof(PageBackgroundColorA),"#222222");
    }
    public Color IconColorA { get; }
    public Color PageBackgroundColorA { get; }
}

我想将这两个都分配给 Application.Current.Resources,但我只知道如何做一个

Application.Current.Resources = new Theme1();

Application.Current.Resources = new Theme2();

如何将两者都分配给 Application.Current.Resources?我认为在 XAML 中有一种方法可以做到这一点,但在 C# 中我找不到任何方法来做到这一点。

解决方法

您可以将它们添加到 MergedDictionaries 属性:

Application.Current.Resources.MergedDictionaries.Add(new Theme1());
Application.Current.Resources.MergedDictionaries.Add(new Theme2());