在代码中设置或修改 ThemeResource [英] Setting or modifying ThemeResource in code
问题描述
我的问题非常针对 Windows 10 商店应用中的 ThemeResources.不幸的是,经典"WPF 中可用的一些内容与此处不同或不可用.
My questions is very specific to ThemeResources in a Windows 10 Store App. Unfortunately several things available in "classic" WPF are different or not available here.
我试图为许多 ui 元素实现的目标:
What I am trying to achieve for lots of ui elements:
- 允许用户使用系统的强调色(在 XAML 中,这将是
{ThemeResource SystemAccentColor}
作为值.) - 允许用户改用自定义/固定颜色.(我可以覆盖资源字典中的
SystemAccentColor
键) - 允许在运行时在系统重音和自定义颜色之间切换(我可以绑定颜色而不是使用资源)
但我还没有找到一个好的解决方案来实现这一切.如果我有自己的带有自定义颜色的资源字典,当用户想切换回系统的强调色时,我不会删除它.并且使用我绑定的属性有一个缺点,即我没有意识到用户是否在应用程序运行时更改了系统设置中的强调色 - 使用 {ThemeResource}
标记确实如此.
But I have not found a good solution to achieve all of this. If I have my own resource dictionary with the custom color, I won't get rid of it when the user would like to switch back to the system's accent color.
And using a property I am binding against has the drawback that I do not realize if the user changes the accent color in the system settings while the app is running - using the {ThemeResource}
markup it does.
任何想法如何正确完成此操作?如果可以从代码中设置 ThemeResource
,我可以为此编写一些行为,但它似乎不可用.
Any ideas how to get this done properly?
If it would be possible to set the ThemeResource
from code I could write some behavior for this, but it seems not to be available.
推荐答案
在 Windows 10 中,名称Accent Color"更改为SystemControlHighlightAccentBrush",它是一个 ThemeResource
In Windows 10, the name "Accent Color" is changed to "SystemControlHighlightAccentBrush", and it's a ThemeResource
使用示例
<TextBlock Foreground="{ThemeResource SystemControlHighlightAccentBrush}"
Text="This is a sample text" />
要覆盖它,只需在 App.xaml 中更改它的值
To override it, simply change value of it in App.xaml
<Application.Resources>
<SolidColorBrush x:Key="SystemControlHighlightAccentBrush" Color="Orange" />
</Application.Resources>
要切换,有点难首先需要在 App.xaml 中为每个主题设置所有颜色
To switch, it's a little bit more difficult First, you need to set all the color for each theme in App.xaml
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.ThemeDictionaries>
<ResourceDictionary x:Key="Default">
<SolidColorBrush x:Key="SystemControlHighlightAccentBrush" Color="Orange" />
</ResourceDictionary>
<ResourceDictionary x:Key="Dark">
<SolidColorBrush x:Key="SystemControlHighlightAccentBrush" Color="Green" />
</ResourceDictionary>
<ResourceDictionary x:Key="Light">
<SolidColorBrush x:Key="SystemControlHighlightAccentBrush" Color="Blue" />
</ResourceDictionary>
</ResourceDictionary.ThemeDictionaries>
</ResourceDictionary>
</Application.Resources>
然后,在页面或者代码后面,你设置相应的主题
Then, in the page or in code behind, you set the corresponding theme
<TextBlock x:Name="TestTextBlock"
Foreground="{ThemeResource SystemControlHighlightAccentBrush}"
RequestedTheme="Dark"
Text="This is a sample text" />
或在 C# 中
TestTextBlock.RequestedTheme = ElementTheme.Dark;
这篇关于在代码中设置或修改 ThemeResource的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!