WPF: How to invert a boolean value using a converter

Exactly as the title suggests, we will be making a converter to invert a boolean value. Why? So you don’t have to create a new property in your view model every time you need to use the inverse of a specific boolean in your templates.

We will be using the same ConverterMarkupExtension class we defined in a previous article. It just helps us avoid having to declare a static resource whenever we want to use the converter.

[ValueConversion(typeof(bool), typeof(bool))]
public class InvertBoolConverter : ConverterMarkupExtension<InvertBoolConverter>
{
    public InvertBoolConverter()
    {
    }
    
    public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value != null && value is bool)
        {
            return !((bool)value);
        }
  
        return true;
    }
    
    public override object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return Convert(value, targetType, parameter, culture);
    }
}

In the following example we have an IsBusy property in the view model that tells us when work is being done and we want to disable a button when that is the case, which we will be doing with the help of our new converter.

<Button
    Content="Do something"
    IsEnabled="{Binding IsBusy, Converter={my:InvertBoolConverter}}"
    Command="{Binding DoSomethingCommand}" />
Nuno Freitas
Posted by Nuno Freitas on April 9, 2014

Related articles