12

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}" />
Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
Taylor Leese
  • 51,004
  • 28
  • 112
  • 141
  • Does this answer your question? [How to bind inverse boolean properties in WPF?](https://stackoverflow.com/questions/1039636/how-to-bind-inverse-boolean-properties-in-wpf) – StayOnTarget May 01 '20 at 20:16

3 Answers3

13

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.

itowlson
  • 73,686
  • 17
  • 161
  • 157
  • 1
    Unfortunately if your already using a value converter in your binding then you have to resort to some type of piping/chaining technique in order to negate the value returned by that value converter. – jpierson Jan 26 '10 at 13:46
5

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}"
xr280xr
  • 12,621
  • 7
  • 81
  • 125
2

Unfortunately, you cannot directly perform operators, such as negation, on the Binding expression... I would recommend using a ValueConverter to invert the boolean.

kiwipom
  • 7,639
  • 37
  • 37