我的项目在整个项目中的所有WPF窗口都使用一个ProjectTheme.xaml文件。 ProjectTheme.xaml文件引用样式主题如下:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<ResourceDictionary.MergedDictionaries>
<!-- In order to modify the project's theme, change this line -->
<ResourceDictionary Source="/MyProject;component/Themes/WPFThemes/Customized.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
所有的WPF窗口都引用了WindowBase.xaml。
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/MyProject;component/View/WindowBase.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
WindowBase.xaml 引用了自定义标题栏 Bar1.xaml。
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/MyProject;component/Themes/WPFThemes/Bar1.xaml" />
</ResourceDictionary.MergedDictionaries>
Bar1.xaml 引用了 ProjectTheme.xaml
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/MyProject;component/ProjectTheme.xaml"/>
</ResourceDictionary.MergedDictionaries>
因此,层次结构如下:
- Window1 引用 WindowBase.xaml
- WindowBase 引用 Bar1.xaml
- Bar1 引用 ProjectTheme.xaml
- ProjectTheme.xaml 引用实际的主题资源文件。
这个工作得很好。 现在我想在运行时动态更改项目主题而不退出应用程序。 假设我有几个主题样式文件:
- Customized.xaml
- Customized1.xaml
- Customized2.xaml
我的问题是,是否可能在运行时动态更新 ProjectTheme.xaml 文件以更改以下行:
<ResourceDictionary Source="/MyProject;component/Themes/WPFThemes/Customized.xaml" />
到
<ResourceDictionary Source="/MyProject;component/Themes/WPFThemes/Customized1.xaml" />
如何实现我的目标? 如果可以,我该怎么做? 如果不行,原因是什么,以及实现目的的最佳(其他)方式是什么?
我已尝试以下方法,但均无法正常工作:样式未发生变化。
方法1
Application.Current.Resources.MergedDictionaries.Clear();
Uri NewTheme = new Uri(@"/MyProject;component/Themes/WPFThemes/Customized2.xaml", UriKind.Relative);
ResourceDictionary dictionary = (ResourceDictionary)Application.LoadComponent(NewTheme);
Application.Current.Resources.MergedDictionaries.Add(dictionary);
方法2
Application.Current.Resources.MergedDictionaries.RemoveAt(0);
Uri NewTheme = new Uri(@"/MyProject;component/Themes/WPFThemes/Customized2.xaml", UriKind.Relative);
ResourceDictionary dictionary = (ResourceDictionary)Application.LoadComponent(NewTheme);
Application.Current.Resources.MergedDictionaries.Insert(0, dictionary);
注意:在我的真实主题样式文件(Customized.xaml...)中,我使用了动态资源和静态资源的组合。这会有影响吗?提前致谢。
DynamicResource
。如果您在转换器中定义颜色,情况如何?<conv:RejectedOrMissedCallColorConverter x:Key ="RejectedOrMissedCallColorConverter" MatchColor ="Red" DefaultColor ="{StaticResource BlackColorBrush}"/>
。我无法在此处使用dynamic... - JobaDiniz