Converter and it’s inverted big brother
Converters are great and can help you in a whole lot of different situations when working with XAML. But as your app grows, the number of converters can also grow. A couple of years back I was developing one of our wpf desktop applications in DIPS and I was using a very common BoolToVisibilityConverter and the big brother: InvertedBoolToVisiblityConverter (not very common in a Xamarin.Forms app, because the visibilities we work with are bool). These two are only a small portion of all of the different types of converters we were using, and for each new converter we needed to add a inverted converter as well.
When I started working on our shared UI library for our mobile apps, I wanted this to be much simpler. I wanted our consumers to use the same converter but to tell it to invert if they needed to. That way we only need to maintain one source for the converter and not having to have 2x converters for each converter.
MarkupExtension
MarkupExtensions are great and very powerful. If you don’t know much about it I recommend you reading this Xamarin doc about it. Essentially, a MarkupExtension is a way for you to provide a value when someone uses it in their XAML. Actually, you are using it all the time if you are using Binding, StaticResource, DynamicResource etc.
Converter as MarkupExtension
I wanted to explore using MarkupExtensions and what I found out is that I can create a converter that implements IMarkupExtension and IValueConverter. This will let my consumers set properties to my converter and use it directly in-line instead of having to define it as a resource and refer it all the time. Win-win! ✌
So, let’s say that we are creating a IsEmptyConverter. This converter should take a string input and return true/false depending on if the string is empty or not.
The converter:
Pretty simple and straight forward. It uses string.IsNullOrEmpty and gives you that true/false back.
Invert it:
Let's use MarkupExtensions! 🎉 Implement IMarkupExtension
What I am doing here is to provide a value of this (which is a IValueConverter) in the ProvideValue method that we need to implement.This means that you can do the following in your XAML:
I have also introduced an Inverted bool property. I use the property to determine if I should invert the output of the converter or not. This means that the consumer can do this to invert it:
The converter is now easy to use and it has the possibility of being inverted without having to create a new converter! 🎉
- You can expand this further and let the consumer choose what kind of objects they want to return instead of it returning true/false. Have a look at this converter to see how you can do that.
- Here is the original source code of the converter that is used as an example in this blog post.