Jake Pearson
Jake Pearson

Reputation: 27717

Bind to not

Is there a super quick way to bind to the inverse of a boolean property? Something like this:

<TextBox Text="Some Text" IsEnabled="{Binding !EnableTextBox}" />

I know I can use a DataTrigger, but I was hoping for a nice shorthand.

Upvotes: 1

Views: 2458

Answers (1)

opedog
opedog

Reputation: 746

When I need to do this, I wrote a simple converter:

public class BoolInverterConverter : IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value is bool)
        {
            return !(bool)value;
        }
        return value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}

<TextBox Text="Some Text" IsEnabled="{Binding EnableTextBox, Converter={StaticResource BoolInverterConverter}}" />

Or a quicker solution would be just to add another read-only bool property to your VM and negate that value.

Upvotes: 4

Related Questions