如何使用DataTrigger重写绑定属性?

时间:2023-01-17 10:50:49

I've got the following XAML used to display detailed information about an item selected in a list view. I want the rectangle to show the standard info color behind the text except when the selected item represents an error message. The code below doesn't work as is and always shows the info color. It works great if I don't specify a Fill for the root <Rectangle /> element.

我得到了以下XAML,用于显示列表视图中选择的项目的详细信息。我想要矩形显示文本后面的标准信息颜色,除非所选项表示错误消息。下面的代码不能正常工作,总是显示信息的颜色。如果我不为根 <矩形 />元素指定填充,效果会很好。

<Rectangle Fill="{DynamicResource {x:Static SystemColors.InfoBrushKey}}" 
           RadiusX="4" RadiusY="4">
  <Rectangle.Style>
    <Style TargetType="{x:Type Rectangle}">
      <Style.Triggers>
        <DataTrigger Binding="{Binding Path=CurrentMessage.Severity"  
                     Value="Error" >
          <Setter Property="Fill" Value="#20FF0000" />
        </DataTrigger>
      </Style.Triggers>
    </Style>
  </Rectangle.Style>
</Rectangle>

The snippet doesn't reflect it, but the real code has quite a few possible status levels for the Severity so I don't want to define a trigger for each possible severity. The logic I want is "Use the info color unless the severity is error, then use red".

代码片段没有反映它,但是真正的代码对于严重性有很多可能的状态级别,所以我不想为每个可能的严重性定义一个触发器。我想要的逻辑是“使用信息颜色,除非严重程度是错误的,然后使用红色”。

I'm sure I've misunderstood some fundamental aspect of WPF but can't seem to pinpoint it. Can someone point me in the right direction so that the data triggers I specify will override the existing Fill value when their conditions are true?

我确信我误解了WPF的一些基本方面,但似乎无法准确地指出它。是否有人能将我指向正确的方向,使我指定的数据触发器在其条件为真时覆盖现有的填充值?

1 个解决方案

#1


10  

You're almost there. Instead of specifying the "default" fill as an attribute on your Rectangle, specify it within the Style:

你差不多了。不要将“默认”填充指定为矩形上的属性,而是在样式中指定:

<Rectangle RadiusX="4" RadiusY="4">
  <Rectangle.Style>
    <Style TargetType="{x:Type Rectangle}">
      <Setter Property="Fill" 
              Value="{DynamicResource {x:Static SystemColors.InfoBrushKey}}" />
      <Style.Triggers>
        <DataTrigger Binding="{Binding Path=CurrentMessage.Severity"  
                     Value="Error" >
          <Setter Property="Fill" Value="#20FF0000" />
        </DataTrigger>
      </Style.Triggers>
    </Style>
  </Rectangle.Style>
</Rectangle>

#1


10  

You're almost there. Instead of specifying the "default" fill as an attribute on your Rectangle, specify it within the Style:

你差不多了。不要将“默认”填充指定为矩形上的属性,而是在样式中指定:

<Rectangle RadiusX="4" RadiusY="4">
  <Rectangle.Style>
    <Style TargetType="{x:Type Rectangle}">
      <Setter Property="Fill" 
              Value="{DynamicResource {x:Static SystemColors.InfoBrushKey}}" />
      <Style.Triggers>
        <DataTrigger Binding="{Binding Path=CurrentMessage.Severity"  
                     Value="Error" >
          <Setter Property="Fill" Value="#20FF0000" />
        </DataTrigger>
      </Style.Triggers>
    </Style>
  </Rectangle.Style>
</Rectangle>