Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I override a bound property with a DataTrigger

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.

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

like image 784
Paul Alexander Avatar asked May 07 '09 06:05

Paul Alexander


1 Answers

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>
like image 175
Matt Hamilton Avatar answered Oct 03 '22 22:10

Matt Hamilton