在运行时切换wpf资源字典

在运行时切换wpf资源字典

本文介绍了在运行时切换wpf资源字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to build a wpf application that allows the user to change the theme at runtime. What I have done so far is create a resourcedictionary with all the colors for the application defined in it and then I am binding to this dictionary in the xaml.

下面是代码我已经用于切换资源字典:

Below is the code I have for switching the resource dictionary:

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

此代码运行正常,我知道它是切换资源字典,但不更新屏幕上已显示的元素。我的问题是:如何刷新或重新绑定屏幕以考虑新的资源字典?

This code runs fine, and I know that it is switching the resource dictionary, but it does not update elements already displayed on the screen. My question is: how can I refresh or rebind the screen to take into account the new resource dictionary?

谢谢

sm

推荐答案

在我的情况下,我只需要更改:

In my case, I simply had to change:

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

to:

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

这篇关于在运行时切换wpf资源字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 16:10