amb*_*rus 4 c# xaml windows-8 windows-runtime windows-store-apps
根据MSDN,设置应用主题的标准方法是设置RequestedTheme="Dark"或RequestedTheme="Light"在顶层Application实例上.
这对于简单的应用程序非常有用,但很多时候我发现自己想要更改单个页面的主题甚至单个控件(例如,以同一应用程序中的以光为主题的文本编辑页面与黑暗主题的图像查看器).
XAML控件具有10或100个视觉状态和颜色定义,并且手动设置每个控件都很繁琐且难以100%正确!
是否有一种简单的方法可以在单个控件上设置暗色或浅色主题?
对于XAML Windows Store应用程序,控件的默认外观在中定义Common/StandardStyles.xaml。如果您曾经看过该文件,将会注意到大量参考文献,例如{StaticResource ApplicationForegroundThemeBrush}。看起来很有希望...
不幸的是,这些“主题画笔”未在您的应用程序中的任何位置定义,并且没有简单的方法为单个控件设置明暗替代。但是,有一个答案。
幸运的是,乔·怀特(Joe White)撰写了一篇很棒的博客文章,主题是默认主题颜色,我将其转变为资源字典,您可以在此处找到它。Dropbox仅执行xml预览,因此您必须重命名该文件。
但是,将这些资源复制到您的应用程序本身并不会帮助。要使用它们,您需要通过外科手术覆盖默认的控件样式才能使用它们!
一种方法是创建一个新的资源字典,例如在Common/CustomStyles.xaml,然后将其合并到应用程序的资源中,如下所示:
<Application
x:Class="My.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
RequestedTheme="Light">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<!--
Styles that define common aspects of the platform look and feel
Required by Visual Studio project and item templates
-->
<ResourceDictionary Source="Common/ThemeColors.xaml"/>
<ResourceDictionary Source="Common/StandardStyles.xaml"/>
<ResourceDictionary Source="Common/CustomStyles.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
Run Code Online (Sandbox Code Playgroud)
请注意,我们的默认主题是Light。如果我们要制作一个Dark主题主题TextBlock,让我们从中复制视觉样式StandardStyles.xaml并将其添加到我们的样式中,CustomStyles.xaml然后进行一些更改。
<Style x:Key="BasicRichTextStyleDark" TargetType="RichTextBlock">
<Setter Property="Foreground" Value="{StaticResource ApplicationForegroundThemeBrushDark}"/>
<Setter Property="FontSize" Value="{StaticResource ControlContentThemeFontSize}"/>
<Setter Property="FontFamily" Value="{StaticResource ContentControlThemeFontFamily}"/>
<Setter Property="TextTrimming" Value="WordEllipsis"/>
<Setter Property="TextWrapping" Value="Wrap"/>
<Setter Property="Typography.StylisticSet20" Value="True"/>
<Setter Property="Typography.DiscretionaryLigatures" Value="True"/>
<Setter Property="Typography.CaseSensitiveForms" Value="True"/>
</Style>
Run Code Online (Sandbox Code Playgroud)
注意,我们已经附加Dark了样式名称和主题画笔定义!您可以通过在CustomStyles.xaml文件中查找并替换"ThemeBrush}"=> 来执行此"ThemeBrushDark}"操作。
现在,您可以创建一个深色主题的文本块,如下所示:
<TextBlock Style="{StaticResource BasicRichTextStyleDark}"/>
Run Code Online (Sandbox Code Playgroud)
当然,您也可以将这种技术用于任何其他类型的控件。有点乏味,但是结果是正确的,并且不比尝试手动定义每种颜色差!
这里没有魔术。我们只是定义一些颜色,并使用我们复制粘贴并修改为使用颜色的一种颜色来覆盖默认样式。
小智 5
令人惊讶的是,似乎没有提到的解决方案只是在各个控制元素上使用RequestedTheme ="Dark"或RequestedTheme ="Light".
我这样做的应用程序,我需要将一些appbarbuttons设置为暗设置(白色前景) - 因为Foreground属性没有将圆和字形本身都设置为白色:
<AppBarButton Label="Reload all articles" RequestedTheme="Dark" >
Run Code Online (Sandbox Code Playgroud)
这样,我只是强制控件使用我决定的主题.