【问题标题】:WPF - Is it possible to negate the result of a data binding expression?WPF - 是否可以否定数据绑定表达式的结果?
【发布时间】:2010-12-23 01:49:16
【问题描述】:

我知道这很好用:

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

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

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

【问题讨论】:

标签: c# .net wpf data-binding


【解决方案1】:

您可以使用 IValueConverter 来做到这一点:

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

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

【讨论】:

  • 不幸的是,如果您已经在绑定中使用了值转换器,那么您必须使用某种类型的管道/链接技术来否定该值转换器返回的值。
【解决方案2】:

如果您想要 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。该参数允许它在转换之前否定布尔值,以防您想要相反的行为。你可以在这样的元素中使用它:

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2010-10-13
      • 2010-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-04
      • 2011-02-14
      • 2011-03-11
      相关资源
      最近更新 更多