简体   繁体   中英

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

I know this works fine:

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

...but what I really want to do is negate the result of the binding expression similar to below (psuedocode). Is this possible?

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

You can do this using an IValueConverter:

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

and use one of these as the Converter of your Binding.

If you want want a result type other than bool, I've recently started using the ConverterParameter to give myself the option of negating the resulting value from my converters. Here's an example:

[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;
    }
    ...

This converter converts a bool to a System.Windows.Visibility. The parameter allows it to negate the bool before converting in case you want the inverse behavior. You could use it in an element like this:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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