簡體   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