我有一个用户控件,它使用如下的画笔资源为控件中的几个元素提供颜色:
<UserControl.Resources>
<SolidColorBrush x:Key="BlackBrush" Color="Black"/>
</UserControl.Resources>
现在,我想使用触发器更改此资源的颜色,以便在发生特定条件时提供高亮显示。
这可能吗?如果是这样,怎么做?
谢谢!
最佳答案
我认为您不能从 xaml 中的触发器更改资源颜色。
您可以在代码隐藏中更改颜色,或者将 SolidColorBrush 中的颜色设置为对象的数据绑定(bind)属性。
SolidColorBrush myBrush = (SolidColorBrush)this.TryFindResource("BlackBrush");
if (myBrush != null)
{
myBrush.Color = Colors.Yellow;
}
否则,您需要根据触发器交换画笔。下面是一个例子:
<Grid Margin="50">
<Grid.Resources>
<SolidColorBrush x:Key="BlackBrush" Color="Black"/>
<SolidColorBrush x:Key="WhiteBrush" Color="White"/>
<Style x:Key="test" TargetType="TextBlock">
<Setter Property="Background" Value="{StaticResource BlackBrush}"/>
<Style.Triggers>
<Trigger Property="Text" Value="white">
<Setter Property="Background" Value="{StaticResource WhiteBrush}"/>
</Trigger>
<Trigger Property="Text" Value="black">
<Setter Property="Background" Value="{StaticResource BlackBrush}"/>
</Trigger>
</Style.Triggers>
</Style>
</Grid.Resources>
<TextBlock
Height="20"
Margin="50"
Padding="50"
Style="{StaticResource test}"
Text="white">
</TextBlock>
</Grid>
这将根据文本值更改背景颜色;如果文本为白色,则背景为白色,黑色,则背景为黑色。
关于.net - 使用触发器更改 SolidcolorBrush 资源的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12754358/