Style triggers in Silverlight

元气小坏坏 提交于 2019-12-03 15:57:43

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!