How to invert a boolean value in XAML with a IValueConverter

Home / How to invert a boolean value in XAML with a IValueConverter

In this post we’ll how is possible to invert a boolean value in our XAML page using a ConverterLet’s say that we have a Label that should be visible only if a boolean property is false. In the next example in our XAML we have a Label with the text bound to MyText and this label should be visible only if the boolean property HideMyText is false:

<Label Text="{Binding MyText}" 
       IsVisible="{Binding HideMyText}">
</Label>

How we can do that? An amateur will create a new property ShowMyText whose value will be:ShowMyText = !HideMyTextIf you want to be a mediocre developer you can stop here because it works but if you want to be a great developer, then this solution is not for you and you should continue to read!

IValueConverter

To solve our problem we need to create a converter that will invert our boolean value. This is really easy, we just need to create a new class BooleanConverter (you can user whatever name you prefer):

public class BooleanConverter : IValueConverter, IMarkupExtension
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return !((bool) value);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value;
    }

    public object ProvideValue(IServiceProvider serviceProvider)
    {
        return this;
    }
}

and then use this new converter in our XAML:

<Label Text="{Binding MyText}" 
       IsVisible="{Binding HideMyText, Converter={converters:BooleanConverter}}">
</Label>

So now in our XAML we have a label that is visible when HideMyText is false. YEAH!You need to write this converter only once and then you can use it every time you need it. It’s amazing!

, , , ,

About Author

Leave a Reply

Your email address will not be published. Required fields are marked *