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 Converter

Let’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:

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):




and then use this new converter in our XAML:

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!

 

Leave a Reply