C# WPF UI框架MahApps切换主题

2022-06-09 21:39:25 浏览数 (1)

概述

本指南将向您介绍MahApps.Metro如何切换主题,所有的MahApps.Metro的主题都包含在单独的资源字典中。

如何使用主题

您可以在以下可用配色方案中进行选择:

代码语言:javascript复制
"Red", "Green", "Blue", "Purple", "Orange", "Lime", "Emerald", "Teal", "Cyan", "Cobalt", "Indigo", "Violet", "Pink", "Magenta", "Crimson", "Amber", "Yellow", "Brown", "Olive", "Steel", "Mauve", "Taupe", "Sienna"

这些基本主题:

代码语言:javascript复制
"Light", "Dark"

通过App.xaml使用主题:

最快的方法是在App.xaml中指定主题资源

代码语言:javascript复制
<Application x:Class="SampleApp"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">
  <Application.Resources>
    <ResourceDictionary>
      <ResourceDictionary.MergedDictionaries>
        <!-- MahApps.Metro resource dictionaries. Make sure that all file names are Case Sensitive! -->
        <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml" />
        <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Fonts.xaml" />
        <!-- Theme setting -->
        <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Themes/Light.Blue.xaml" />
      </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
  </Application.Resources>
</Application>

通过主题管理器使用主题:

MahApps.Metro有一个ThemeManager类,可以使用后台代码更改主题。可以在一行中完成,如下所示:

代码语言:javascript复制
using ControlzEx.Theming;

public partial class SampleApp : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        // Set the application theme to Dark.Green
        ThemeManager.Current.ChangeTheme(this, "Dark.Green");
    }
}

在与应用程序主窗口不同的窗口上

和MahApps在一样,对于MetroWindow,你可以有不同的主题。主窗口或任何其他MetroWindows将在应用程序中保留指定的主题。

代码语言:javascript复制
<Controls:MetroWindow.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Themes/Dark.Red.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Controls:MetroWindow.Resources>

您也可以使用TheManager执行此操作,如下所示:

代码语言:javascript复制
using ControlzEx.Theming;

public partial class MainWindow : MetroWindow
{
    public void MainWindow()
    {
        InitializeComponent();

        // Set the window theme to Dark.Red
        ThemeManager.Current.ChangeTheme(this, "Dark.Red");
    }
}

创建自定义主题

MahApps的另一个不错的功能。Metro将使用自定义创建的主题或运行时创建的主题。

声明

翻译自:https://mahapps.com/docs/themes/usage#on-a-window-different-to-your-applications-main-window

0 人点赞