我在我的应用程序中实现了浅色/深色主题,用户可以按浅色或深色按钮,所有应用程序颜色都会改变。我通过将 SolidColorBrush 绑定(bind)到每个元素的背景和前景来实现此目的,例如
在 View 模型中:
private SolidColorBrush fontColour;
public SolidColorBrush FontColour
{
get { return fontColour; }
set
{
fontColour = value;
OnPropertyChanged(nameof(FontColour));
}
}
在 xaml 中:
<TextBox Text="{Binding EventLog}"
Foreground="{Binding FontColour}"
Background="{Binding ColourTheme5}"/>
这按预期工作。但是,当我尝试在 TextBox.Resources 中执行相同的操作时,绑定(bind)根本不起作用,例如
(TextControlForegroundPointerOver 的绑定(bind)不起作用)
<TextBox Text="{Binding EventLog}"
Foreground="{Binding FontColour}"
Background="{Binding ColourTheme5}">
<TextBox.Resources>
<SolidColorBrush x:Key="TextControlForegroundPointerOver"
Color="{Binding FontColour}"
Opacity="1" />
</TextBox.Resources>
</TextBox>
最佳答案
我几乎可以肯定,TextBox.Resources
不是 DependencyProperty,因此无法绑定(bind)。
如果您想在编译时设置它,请使用代码初始化(就像您放在最底部的示例一样)。
如果您想在运行时设置它,则必须在窗口/用户控件(您放置 TextBox 的位置)的构造函数中以编程方式进行设置。这应该可行。
编辑:我错过了问题的“浅色/深色主题”部分,因此我想添加:
Windows 社区工具包中有关于主题的重要部分、更多文档以及示例应用程序中的一部分,您可以在 https://learn.microsoft.com/en-us/windows/communitytoolkit/helpers/themelistener 找到。 .
关于TextBox 资源中的 C# UWP 数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68145379/