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 = !HideMyText
If 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>
IMPORTANT: at the top of your XAML, remember to add this line:
xmlns:converters="clr-namespace:YourProjectName.FolderWithTheConverter"
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!
June 13, 2020 @ 3:55 am
Works perfectly, Just a suggestion, people who read this are beginners so they probably don’t know that they need to add the xmlns:converters=”clr-namespace:{ProjectName}” on their Xaml page.
Thanks.
November 17, 2019 @ 1:02 pm
Thank you so much. Its working.
October 4, 2019 @ 2:42 pm
It is not working
October 4, 2019 @ 9:50 pm
What is not working?
What problem do you have?