相关疑难解决方法(0)

WPF动态更改资源文件和主题

我的项目在整个项目中为所有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是

  • 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" />
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)

wpf mvvm c#-4.0

10
推荐指数
1
解决办法
2万
查看次数

标签 统计

c#-4.0 ×1

mvvm ×1

wpf ×1