UWP应用程序中的自定义主题

时间:2016-09-16 14:18:13

标签: c# themes uwp

我正在开发一个UWP应用程序,我想从文件中动态设置主题(包含颜色代码)。

我创建的文件是一个XML文件,其节点包含映射到应用程序控件的颜色代码。

用户可以更新提供的XML文件中的颜色代码,这应该反映应用程序中的主题更改。

我可以为此文件设置任何自定义位置,以便用户可以编辑文件的内容吗?

这是在UWP应用程序中实现主题的正确方法。

另外,我是UWP技术的新手。

提前致谢。

1 个答案:

答案 0 :(得分:8)

默认情况下,UWP应用支持两个主题 - LightDark

您可以在App.xaml中指定应用的主题,方法是将RequestedTheme属性设置为其中一个值(默认设置为Light)或者使用App.xaml.cs的App构造函数中的RequestedTheme = ApplicationTheme.Light;(稍后将其更改将导致抛出异常)。

如果您未设置RequestedTheme属性,则会在任何W10移动设备或运行周年纪念更新和更新版本的W10 PC上反映Settings > Personalization > Colors中设置的主题。在较旧的Windows 10桌面版本上,它将是Light

您还可以设置默认情况下设置为FrameworkElement的任何特定ElementTheme.Default的主题,以便从其父级继承主题。

<StackPanel RequestedTheme="Light">
   <TextBlock>Text using light theme.</TextBlock>
   <TextBlock RequestedTheme="Dark">Text using dark theme.</TextBlock>
</StackPanel>

对于颜色自定义UWP通常也使用用户在Settings > Personalization > Colors中指定的强调颜色。

要反映在设置应用中为某些元素指定自定义颜色时设置的主题和重音颜色,您必须使用ThemeResource。您可以使用预定义的XAML主题资源,例如此边框的背景颜色在#FFFFFFFF主题中为Light,在#FF000000主题中为Dark

<Border Background="{ThemeResource SystemControlBackgroundAltHighBrush}"/>

或者您可以使用SystemControlBackgroundAccentBrush来反映在“设置”应用中选择的“强调”颜色。

您还可以编写自己的theme dictionary,为每个主题指定颜色。以下是一个简单主题词典的示例:

<ResourceDictionary.ThemeDictionaries>
    <ResourceDictionary x:Key="Light">
        <SolidColorBrush x:Key="MyButtonBackgroundThemeBrush" Color="White"/
        <SolidColorBrush x:Key="MyButtonForegroundThemeBrush" Color="Black"/>
    </ResourceDictionary>
    <ResourceDictionary x:Key="Dark">
        <SolidColorBrush x:Key="MyButtonBackgroundThemeBrush" Color="Black"/>
        <SolidColorBrush x:Key="MyButtonForegroundThemeBrush" Color="White"/>
    </ResourceDictionary>
</ResourceDictionary.ThemeDictionaries>

你会像这样使用它:

<Button Content="Themed button"
        Background="{ThemeResource MyButtonBackgroundThemeBrush}"
        Foreground="{ThemeResource MyButtonForegroundThemeBrush}"/
        />

按钮的背景为WhiteBlack主题中的前景为Light,而BlackWhite位于Dark 1}}主题。

您可以详细了解ThemeResource,主题,HighContrast主题和默认主题资源here

另外,我建议您在第9频道观看this视频,即使使用HighContrast主题,也会解释XAML主题。