c# - 在运行时切换 wpf 资源字典

标签 c# wpf data-binding xaml resourcedictionary

我正在尝试构建一个允许用户在运行时更改主题的 wpf 应用程序。到目前为止,我所做的是创建一个资源字典,其中定义了应用程序的所有颜色,然后我在 xaml 中绑定(bind)到这个字典。

下面是我用来切换资源字典的代码:

if (System.IO.File.Exists(fileName))
{
   using (FileStream fs = new FileStream(fileName, FileMode.Open))
   {
      ResourceDictionary dic = (ResourceDictionary)XamlReader.Load(fs);
      Resources.MergedDictionaries.Clear();
      Resources.MergedDictionaries.Add(dic);
   }
}

这段代码运行良好,我知道它正在切换资源字典,但它不会更新已经显示在屏幕上的元素。我的问题是:如何刷新或重新绑定(bind)屏幕以考虑新的资源字典?

谢谢

最佳答案

就我而言,我只需更改:

Resources.MergedDictionaries.Clear();
Resources.MergedDictionaries.Add(dic);

到:

Application.Current.Resources.MergedDictionaries.Clear();
Application.Current.Resources.MergedDictionaries.Add(dic);

关于c# - 在运行时切换 wpf 资源字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2381085/

相关文章:

WPF ScrollView 默认滚动到底部

c# - 如何在 WPF 中使用 SQLite

html - 将 Angular JS ui-bootstrap 下拉切换绑定(bind)到 ng-model

c# - 绑定(bind)集合的子集

c# - POST 和 GET 方法可以进入不同的 View 吗?

c# - Xamarin MvvmCross iOS Bool to Color ValueConverter 不改变标签文本颜色

c# - 在 C# 中将方法调用中的字符串数组初始化为参数

c# Selenium Chromedriver 打开错误的 url onload

c# - 为什么使用带破折号图案的笔会导致 WPF 自定义 2D 绘图中出现巨大(!)性能下降?

android - 在 com.example.widget.MyTableRow 上找不到值类型为 java.lang.String 的属性 'app:rowContentText' 的 getter