我的项目在整个项目中为所有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>
Run Code Online (Sandbox Code Playgroud)
所有WPF Windows引用WindowBase.xaml
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/MyProject;component/View/WindowBase.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
Run Code Online (Sandbox Code Playgroud)
WindowBase.xaml引用自定义标题栏Bar1.xaml
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/MyProject;component/Themes/WPFThemes/Bar1.xaml" />
</ResourceDictionary.MergedDictionaries>
Run Code Online (Sandbox Code Playgroud)
Bar1.xaml引用了ProjectTheme.xaml
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/MyProject;component/ProjectTheme.xaml"/>
</ResourceDictionary.MergedDictionaries>
Run Code Online (Sandbox Code Playgroud)
所以heriarchy是
这很好用.现在我想在运行时动态更改项目主题而不退出应用程序.假设我有几个主题样式文件
我的问题是,是否可以在运行时动态更新ProjectTheme.xaml文件以更改行
<ResourceDictionary Source="/MyProject;component/Themes/WPFThemes/Customized.xaml" />
Run Code Online (Sandbox Code Playgroud)
至
<ResourceDictionary Source="/MyProject;component/Themes/WPFThemes/Customized1.xaml" />
Run Code Online (Sandbox Code Playgroud)
实现我的目标?如果是,我该怎么办?如果不是,原因是什么,以及实现目标的最佳(其他)方式是什么?
我尝试了以下但没有一个工作:风格不会改变.
方式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);
Run Code Online (Sandbox Code Playgroud)
方式2
Application.Current.Resources.MergedDictionaries.RemoveAt(0);
Uri NewTheme = …Run Code Online (Sandbox Code Playgroud)