【发布时间】:2016-08-03 04:48:28
【问题描述】:
我正在使用Windows.UI.ViewManagement.UISettings 来获取系统强调色,但这个类似乎没有任何用于明暗模式的方法或属性。我找不到此功能的文档,我该如何检测?
PS:我正在制作一个无法访问 Windows.UI.Xaml 命名空间的 JS 应用程序。
【问题讨论】:
标签: windows uwp windows-10-universal
我正在使用Windows.UI.ViewManagement.UISettings 来获取系统强调色,但这个类似乎没有任何用于明暗模式的方法或属性。我找不到此功能的文档,我该如何检测?
PS:我正在制作一个无法访问 Windows.UI.Xaml 命名空间的 JS 应用程序。
【问题讨论】:
标签: windows uwp windows-10-universal
您可以在解决方案中创建一个 Windows 运行时组件项目,从那里访问 Windows.UI.Xaml 命名空间。添加一个方法来像这样检查当前的 ApplicationTheme。
public sealed class Test
{
public static string CurrentTheme()
{
var isDark = Application.Current.RequestedTheme == ApplicationTheme.Dark;
if (isDark)
return "Dark";
return "Light";
}
}
在您的 javascript 应用程序项目中添加对 Windows 运行时组件项目的引用,您可以在任何需要检查应用程序主题的地方调用此方法。查看 here 了解创建 Windows 运行时组件的演练。
【讨论】:
我找到了一个更简单的解决方案,它也应该适用于 JavaScript 应用程序,而不需要 Windows 运行时组件 - UISettings class:
var uiSettings = new Windows.UI.ViewManagement.UISettings();
var color = uiSettings.getColorValue(
Windows.UI.ViewManagement.UIColorType.background
);
您获得的颜色是 black 用于 dark 主题或 white 用于 light 主题。
该课程还有非常有用的事件ColorValuesChanged,您可以将其用于observe theme changes at runtime。
【讨论】:
wscript?
对于 Windows 10,注册表路径 HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize 中的 AppsUseLightTheme 属性值指定 Windows 处于暗模式还是亮模式。
【讨论】:
AppsUseLightTheme 值可能完全丢失。在这种情况下,您应该退回到轻量模式。 (在较旧的 Windows 10 系统上发生过;Microsoft 本身的 IE Test VM 映像附带的系统)。
在 Windows 周年更新之前,您无法做到这一点。应用程序主题始终是您在 App.xaml 文件中设置的主题:
<Application
...
RequestedTheme="Dark">
</Application>
现在有了新的周年更新,您可以从App.xaml 文件中删除这一行,这将使应用程序尊重用户的系统设置。
RequestedTheme 枚举实际上具有三个值 - Dark、Light 和 Default。 Default是反映系统设置的值,Dark和Light强制主题。
如果您想在 App 的 RequestedTheme 为 Default 时实际检测代码中的当前主题,您可能需要检查诸如 SystemAltHighColor 之类的颜色资源的值,因为这会让您了解当前设置的主题。
【讨论】:
ThemeResources 已在 8.1 中引入,它们的行为在 W10 中类似。因此,您可以在 ThemeDictionaries 中定义合适的资源来负责可用的 Themes,然后当您想知道当前是哪个 Theme 时可以检查定义的资源用过的。
代码将与this answer 中的代码非常相似。
【讨论】:
如果您想在 PowerShell 中获取值,可以使用以下代码:
(New-Object Windows.UI.ViewManagement.UISettings).GetColorValue("background")
【讨论】:
如果为当前用户启用了主题,您可以读取注册表并从那里获取设置。像这样的...
private const string RegistryKeyPath = @"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize";
private const string RegistryValueName = "AppsUseLightTheme";
private static ApplicationTheme GetWindowsTheme()
{
using var key = Registry.CurrentUser.OpenSubKey(RegistryKeyPath);
var registryValueObject = key?.GetValue(RegistryValueName);
if (registryValueObject == null)
{
return ApplicationTheme.Light;
}
var registryValue = (int)registryValueObject;
return registryValue > 0 ? ApplicationTheme.Light : ApplicationTheme.Dark;
}
完整的例子可以在这个链接中找到 https://engy.us/blog/2018/10/20/dark-theme-in-wpf/
【讨论】: