如何在代码隐藏中创建ResourceDictionary

本文关键字:创建 ResourceDictionary 隐藏 代码 | 更新日期: 2023-09-27 18:01:50

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:sys="clr-namespace:System;assembly=mscorlib">
    <sys:String x:Key="one">ONE</sys:String>
    <sys:String x:Key="two">TWO</sys:String>
    <sys:String x:Key="three">THREE</sys:String>
</ResourceDictionary>

现在想在WPF中使用c#通过代码后面动态创建资源ResourceDictionary。有可能这样做吗?

如何在代码隐藏中创建ResourceDictionary

public MainWindow()
    {
        InitializeComponent();
        DataContext = new MainViewModel();
        ResourceDictionary rd = new ResourceDictionary();
        rd.Add("one", "ONE");
        rd.Add("two", "TWO");
        rd.Add("three", "THREE");
        this.Resources.MergedDictionaries.Add(rd);
    }

您看过资源词典了吗?新增方法- http://msdn.microsoft.com/en-us/library/ms521848.aspx?