views:

1602

answers:

1

Hi,

I am trying to use style triggers in silverlight like so:

   <Path Canvas.Top="20" Stroke="#FF808080" Data="M 0,20 20,0 40,20 Z" StrokeLineJoin="Round">
        <Path.Style>
            <Style TargetType="{x:Type Path}">
                <Setter Property="Fill" Value="DarkGray"/>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding ElementName=userControl, Path=PumpRunning}" Value="True">
                        <Setter Property="Fill" Value="DarkGreen"/>        
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Path.Style>
    </Path>

I want to do this so that the fill value of the path changes if the pump is running or not. The problem is that style triggers are not supported in silverlight!

So is there anyway round this? Is there some way of doing this in code? I have looked into it but I am stumped.

Thanks

Ian

+4  A: 

A custom value converter will achieve a similar goal.

 public class BoolToBrushConverter : IValueConverter
 {
  public Brush FalseBrush { get; set; }
  public Brush TrueBrush { get; set; }

  public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
  {
   if (value == null)
    return FalseBrush;
   else
    return (bool)value ? TrueBrush : FalseBrush;
  }

  public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
  {
   throw new NotImplementedException("This converter only works for one way binding");
  }
 }

With this converter in place you can adjust your XAML to:-

 <Path Canvas.Top="20" Stroke="#FF808080" Data="M 0,20 20,0 40,20 Z" StrokeLineJoin="Round">
  <Path.Fill>
   <Binding Path="PumpRunning" ElementName="userControl">
    <Binding.Converter>
     <local:BoolToBrushConverter
      FalseBrush="DarkGray" TrueBrush="DarkGreen" />
    </Binding.Converter>
   </Binding>
  </Path.Fill>
 </Path>

Note that since your color choice was local to your Path definition I've embedded an instance of the Converter directly into my Path definition thus acheiving the same semantic. However if you require a number of these conversions using the same pair colors you can just as easily place the Converter instance in a page resource and use the normal shorthand binding syntax.

AnthonyWJones