繁体   English   中英

WPF - 是否有可能否定数据绑定表达式的结果?

[英]WPF - Is it possible to negate the result of a data binding expression?

我知道这很好用:

<TextBox IsEnabled="{Binding ElementName=myRadioButton, Path=IsChecked}" />

...但我真正想做的是否定类似于下面的结合表达式的结果(伪代码)。 这可能吗?

<TextBox IsEnabled="!{Binding ElementName=myRadioButton, Path=IsChecked}" />

您可以使用IValueConverter执行此操作:

public class NegatingConverter : IValueConverter
{
  public object Convert(object value, ...)
  {
    return !((bool)value);
  }
}

并使用其中一个作为绑定的转换器。

如果你想要一个除bool之外的结果类型,我最近开始使用ConverterParameter给自己选择否定转换器的结果值。 这是一个例子:

[ValueConversion(typeof(bool), typeof(System.Windows.Visibility))]
public class BooleanVisibilityConverter : IValueConverter
{
    System.Windows.Visibility _visibilityWhenFalse = System.Windows.Visibility.Collapsed;

    /// <summary>
    /// Gets or sets the <see cref="System.Windows.Visibility"/> value to use when the value is false. Defaults to collapsed.
    /// </summary>
    public System.Windows.Visibility VisibilityWhenFalse
    {
        get { return _visibilityWhenFalse; }
        set { _visibilityWhenFalse = value; }
    }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        bool negateValue;
        Boolean.TryParse(parameter as string, out negateValue);

        bool val = negateValue ^ (bool)value;  //Negate the value using XOR
        return val ? System.Windows.Visibility.Visible : _visibilityWhenFalse;
    }
    ...

此转换器将bool转换为System.Windows.Visibility。 如果您想要反向行为,该参数允许它在转换之前否定bool。 你可以在这样的元素中使用它:

Visibility="{Binding Path=MyBooleanProperty, Converter={StaticResource boolVisibilityConverter}, ConverterParameter=true}"

不幸的是,你不能直接在Binding表达式上执行运算符,例如否定...我建议使用ValueConverter来反转布尔值。

暂无
暂无

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

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