繁体   English   中英

使用转换器将颜色绑定到布尔值不会更新

[英]Binding color to bool using converter does not get updated

我有一个 WPF 项目。

我想根据我的视图模型的布尔值画一个边框。 我写了一个到 bool 属性的绑定,该属性得到更新,并且有一个从 bool 到某个画笔的特殊转换器。 一切都正确,但颜色没有出现。

我制作了一个示例应用程序来显示该问题:

  <StackPanel>
    <Border BorderThickness="3" BorderBrush="{Binding ElementName=OnOffSwitch, Path=IsChecked, Converter={StaticResource BoolToGreen}, Mode=OneWay}">
        <TextBlock >
            <Run Text="The option is " />
            <Run Text="{Binding ElementName=OnOffSwitch, Path=IsChecked, Mode=OneWay}" />
            <Run Text=" Color should be " />
            <Run Text="{Binding  ElementName=OnOffSwitch, Path=IsChecked, Mode=OneWay, Converter={StaticResource BoolToGreen}}" />
        </TextBlock>
    </Border>
    <CheckBox x:Name="OnOffSwitch" Content="Green" IsChecked="{Binding OnOff}" />
</StackPanel>

我的转换器如下所示:

[ValueConversion(typeof(bool), typeof(Brush))]
public class BoolToGreenColorConverter : IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter,
        System.Globalization.CultureInfo culture)
    {
        return (bool)value ? System.Windows.Media.Colors.Green : System.Windows.Media.Colors.Red;
    }
    //...
}

这是它在运行应用程序时的样子: 在此处输入图像描述

我还尝试了其他 colors,例如文本块背景。 它也不起作用。 我在哪里错过了什么?

您的转换器应返回System.Windows.Media.Brushes.Green而不是Colors.Green

public object Convert(object value, Type targetType, object parameter,
    System.Globalization.CultureInfo culture)
{
    return (bool)value ? System.Windows.Media.Brushes.Green : System.Windows.Media.Brushes.Red;
}

BorderBrush只能设置为Brush而不能设置为Color

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM