如何以编程方式检查Windows Phone 8.1中当前设置的主题?

时间:2014-07-19 22:00:57

标签: windows-phone-8.1 uwp

我想检查用户是否设置了浅色或深色主题。是否可以在Windows Phone 8.1(商店应用程序)中以编程方式执行此操作。

2 个答案:

答案 0 :(得分:7)

MSDN处,您可以找到示例代码,您可以通过比较资源来确定当前主题。例如:

private bool IsDarkTheme()
{ return (double)Application.Current.Resources["PhoneDarkThemeOpacity"] > 0; }

但是 - 我在WP8.1运行时遇到了运行上述行的一些问题 - 它找不到请求的密钥。事实证明 - 上面的代码将有效only on WP8.1 Silverlight (also WP8.0)

但是(再次),没有任何东西挡在路上to define your own ThemeResource并检查它的状态:

在app.xaml中 - 定义一些 ThemeResources

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.ThemeDictionaries>
            <ResourceDictionary x:Key="Light">
                <x:Boolean x:Key="IsDarkTheme">false</x:Boolean>
            </ResourceDictionary>
            <ResourceDictionary x:Key="Dark">
                <x:Boolean x:Key="IsDarkTheme">true</x:Boolean>
            </ResourceDictionary>
            <ResourceDictionary x:Key="Default">
                <x:Boolean x:Key="IsDarkTheme">false</x:Boolean>
            </ResourceDictionary>
        </ResourceDictionary.ThemeDictionaries>
    </ResourceDictionary>
</Application.Resources>

然后您可以在代码中使用例如属性:

public bool IsDarkTheme { get { return (bool)Application.Current.Resources["IsDarkTheme"]; } }

另请注意,在某些情况下,您可能需要检查 HighContrast - 根据MSDN,您可以通过选中AccessibilitySettings class或扩展您自己创建的 ThemeResource by HighContrast值

答案 1 :(得分:3)

要检查哪个主题处于活动状态,您可以使用Application对象MSDN的RequestedTheme属性

var isDark = Application.Current.RequestedTheme == ApplicationTheme.Dark;