Style object based on binding bool attribute in wpf

后端 未结 2 779
天涯浪人
天涯浪人 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:17

    First of all you don't need any Binding for what you are trying to do. DataTrigger is enough. In the example below IsCyan is a boolean property of ViewModel. But Background of TextBlock is not bound at all.

               <TextBlock Text="Inside content">
                    <TextBlock.Style>
                        <Style TargetType="TextBlock">
                            <Style.Triggers>
                                <DataTrigger Binding="{Binding IsCyan}" Value="True">
                                    <Setter Property="Background" Value="DarkCyan"/>
                                </DataTrigger>
                                <DataTrigger Binding="{Binding IsCyan}" Value="False">
                                    <Setter Property="Background" Value="DarkGoldenrod"/>
                                </DataTrigger>
                            </Style.Triggers>
                        </Style>
                    </TextBlock.Style>
                </TextBlock>
    

    But if at all you need Binding, solution by the user benPearce to use Converter is the way to go.

    0 讨论(0)
  • 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;
      }
    }
    
    0 讨论(0)
提交回复
热议问题