Style object based on binding bool attribute in wpf

后端 未结 2 780
天涯浪人
天涯浪人 2021-01-29 05:38

How can change the fill color of an object I\'m being to in my mvvm setup using xaml in wpf. I want to change the fill color to red when the attribute being bound to is set to

2条回答
  •  深忆病人
    2021-01-29 06:23

    You need to use an IValueConverter on the binding.

    BackgroundColor="{Binding Path=IsRound, Converter={StaticResource BoolToFillColorConverter}}"
    
    public class BoolToFillColorConverter: IValueConverter
    {
      public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
          bool b;
          if (bool.TryParse(value, out b))
          {
            if (b) return Red
            else return Blue;
          }
          else
          {
            return SomeDefaultColour;
          }
      public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
      {
        return null;
      }
    }
    

提交回复
热议问题