×

WPF 根据系统主题自动切换浅色与深色模式

独孤求败 独孤求败 发表于2026-04-13 11:10:21 浏览9 评论0

抢沙发发表评论

WPF 根据系统主题自动切换浅色与深色模式

控件名:Resources

作   者:WPFDevelopersOrg - 驚鏵

原文链接[1]:https://github.com/WPFDevelopersOrg/WPFDevelopers

码云链接[2]:https://gitee.com/WPFDevelopersOrg/WPFDevelopers

  • 框架支持.NET4 至 .NET8
  • Visual Studio 2022;
最新 WPFDevelopers 1.1.0.3-preview4  的 Nuget 预览包
1. 修改 ThemeType.cs
  • 新增 Default,用于标识自动跟随系统。
    public enum ThemeType
    {
        Default,
        Light,
        Dark,
    }
2. 修改 Resources.cs
  • 新增 IsWindows10OrLater 方法用于检测当前操作系统是否是 Win10 或者更高版本。
  • 先使用注册表来获得Windows 版本。如果注册表获取失败,然后使用 Environment.OSVersion 属性来获取操作系统的版本。
        bool IsWindows10OrLater()
        {
            using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion"))
            {
                object value = key?.GetValue("CurrentMajorVersionNumber");
                if (value != null && int.TryParse(value.ToString(), out int majorVersion))
                {
                    return majorVersion >= 10;
                }
            }
            Version version = Environment.OSVersion.Version;
            return version.Major >= 10
        }
  • Theme 为 Default 跟随系统主题,并且当前操作系统是 Win10 或更高版本时注册 SystemEvents.UserPreferenceChanged 事件并监听 e.Category == UserPreferenceCategory.General 时调用 IsDarkMode() 方法用于判断操作系统是否为暗黑模式。
  • 系统切换主题模式的时候则会触发 UserPreferenceChanged 事件。
if (Theme == ThemeType.Default && IsWindows10OrLater())
{
    SystemEvents.UserPreferenceChanged += OnUserPreferenceChanged;
    ApplyTheme();
    return;
}
if(Theme == ThemeType.Default)
    Theme = ThemeType.Light;

private void OnUserPreferenceChanged(object sender, UserPreferenceChangedEventArgs e)
 {
     if (e.Category == UserPreferenceCategory.General)
     {
         ApplyTheme();
     }
 }

bool IsDarkMode()
{
    conststring registryKey = @"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize";
    conststring registryValue = "AppsUseLightTheme";
    try
    {
        varvalue = (int)Registry.GetValue(registryKey, registryValue, 1);
        returnvalue == 0
    }
    catch
    {
        returnfalse
    }
}
void ApplyTheme()
{
    var isDarkMode = IsDarkMode();
    var theme = isDarkMode == true ? ThemeType.Dark : ThemeType.Light;
    if(Theme != theme)
        Theme = theme;
}
2. 修改 App.xaml
<Application
    x:Class="WPFDevelopers.Samples.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:avalonedit="http://icsharpcode.net/sharpdevelop/avalonedit"
    xmlns:wd="https://github.com/WPFDevelopersOrg/WPFDevelopers"
    ShutdownMode="OnMainWindowClose"
    StartupUri="MainWindow.xaml">

    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/WPFDevelopers;component/Themes/Theme.xaml" />
                <!--  需要注意 wd:Resources 必须在Theme.xaml后  -->
                <!--
                    默认情况下,Theme 会跟随系统主题(适用于 Windows 10 及以上版本),自动切换为 Light 或 Dark 模式。
                    若要手动设置为 Light 模式,可以使用 Theme="Light"。
                    你还可以自定义主题色,使用 Color="Fuchsia"(例如设置为 Fuchsia)
                -->

                <wd:Resources />
              </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

GitHub 源码地址[3]

Gitee 源码地址[4]

图片

参考资料

1] 

原文链接: https://github.com/WPFDevelopersOrg/WPFDevelopers

[2] 

码云链接: https://gitee.com/WPFDevelopersOrg/WPFDevelopers

[3] 

GitHub 源码地址: https://github.com/WPFDevelopersOrg/WPFDevelopers/tree/dev/src/WPFDevelopers.Samples.Shared/Resources.cs

[4] 

Gitee 源码地址: https://gitee.com/WPFDevelopersOrg/WPFDevelopers/tree/dev/src/WPFDevelopers.Samples.Shared/Resources.cs


群贤毕至

访客