.net - 使用触发器更改 SolidcolorBrush 资源的颜色?

标签 .net wpf silverlight xaml

我有一个用户控件,它使用如下的画笔资源为控件中的几个元素提供颜色:

        <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/

相关文章:

c# - 读取/写入文件的最大并行度是多少?

.net - 如何使用此 Linq2Sql 减少数据库往返次数?

c# - Caliburn 在 ComboBox 上重置 SelectedIndex

asp.net - 为什么 Application_Start 在 Global.asax 中多次触发?

c# - Silverlight 中 PictureBox 的替代品是什么?

xml - 通过 WCF 与 WebClient 下载图像

c# - 使用一个 TKey 数组对多个 TValue 数组进行排序

c# - 使用动态发出的 POCO 进行快速序列化和反序列化

c# - 将模型中的异步更改通知 ViewModel

c# - WPF 自定义控件 : DependencyProperty of Collection type