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

Ips*_*aur 2 c# themes uwp

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

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

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

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

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

此外,我是UWP技术的新手.

提前致谢.

Mar*_*ský 9

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

您可以指定在您的应用程序的主题,App.xaml通过设置RequestedTheme属性值中的任一个(将其设置为Light默认),或在App.xaml.cs使用应用程序的构造函数RequestedTheme = ApplicationTheme.Light;(改变它的任何地方以后会导致引发异常).

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

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

<StackPanel RequestedTheme="Light">
   <TextBlock>Text using light theme.</TextBlock>
   <TextBlock RequestedTheme="Dark">Text using dark theme.</TextBlock>
</StackPanel>
Run Code Online (Sandbox Code Playgroud)

对于颜色定制,UWP通常也使用用户指定的强调颜色Settings > Personalization > Colors.

要反映在"设置"应用中为某些元素指定自定义颜色的主题和强调色设置,您必须使用ThemeResource.您可以使用预定义的XAML主题的资源,例如此边框的背景颜色将#FFFFFFFFLight主题#FF000000Dark的主题.

<Border Background="{ThemeResource SystemControlBackgroundAltHighBrush}"/>
Run Code Online (Sandbox Code Playgroud)

或者您可以使用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>
Run Code Online (Sandbox Code Playgroud)

你会像这样使用它:

<Button Content="Themed button"
        Background="{ThemeResource MyButtonBackgroundThemeBrush}"
        Foreground="{ThemeResource MyButtonForegroundThemeBrush}"/
        />
Run Code Online (Sandbox Code Playgroud)

按钮的背景将是White和前景将是BlackLight主题,而BlackWhiteDark主题.

您可以在此处阅读有关ThemeResource主题,HighContrast主题和默认主题资源的更多信息.

另外,我建议你在第9频道观看这个视频,即使主题也是XAML HighContrast主题.