Writing XAML Value Converters for Xamarin Forms

Explanation

XAML isn’t perfect. It is often missing some tools that honestly should just be a party of the set. For example, express if a value is null or not null.

What we will want to use is the IValueConverter interface. This interface has two methods defined:object Convert

object Convert(object value, Type targetType, object parameter, CultureInfo culture);
object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture);

These two methods are used to convert a value from one type to another. The first method is called to convert your base value. The second one is if you have two way binding, to convert it back. This is not always necessary unless you have a specific use case that can be converted from one value to another, such as Hex color to Color object and vice versa.

Writing the code

Here is the converter that we are going to implement:
    public class IsNullConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

As of right now, the methods are set to throw on call. This is a good template to start out with as when we use our ConvertBack, we want it to throw an error in the case that we accidentally set two-way binding.

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value == null;
        }

For this functionality, all we need to do is return if our value is null. If it is, it will return true and false if it is not. Pretty simple right?

How to use it?

So to use this handy dandy tool, we need to declare it in a resource dictionary. I prefer to do this in the Appl.xaml, but you can define this in your individual pages if you prefer. It depends on where this is going to be used.

We need to declare a new namespace to look against, then we will bind it as a static resource to be used using a key. In the follow block, you will see that we declare a new namespace called helpers. We connect that to the namespace that our IValueConverter is in.

<?xml version="1.0" encoding="utf-8" ?>
<Application xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="ValueConverterExample.App"
             xmlns:helpers="clr-namespace:ValueConverterExample.Helpers">
    <Application.Resources>
        <ResourceDictionary>
            <helpers:IsNullConverter x:Key="IsNull"/>
        </ResourceDictionary>
    </Application.Resources>
</Application>

Inside of the Application.Resources, we define our ResourceDictionary. Inside of this, we can define our IsNullConverter. Notice the helpers: in front of the class name. This is defining which namespace can find this. Also, newer versions of Visual Studio can intellisense most of this for you.

Okay… Now how can we use it practically?

So inside of our pages and or our custom controls, we can access this without extra work (assuming you declared this in the App.xaml).

Anytime we use a binding, we can use this. Your binding value is what will be passed inside of the first parameter in the method we defined for Convert.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:ValueConverterExample"
             x:Class="ValueConverterExample.MainPage">

    <StackLayout>
        <Label Text="Should see this" IsVisible="{Binding NullString, Converter={StaticResource Key=IsNull}}"/>
        <Label Text="Should not see this" IsVisible="{Binding NotNullString, Converter={StaticResource Key=IsNull}}"/>
    </StackLayout>

</ContentPage>

I have two strings defined in a model, one that is null and one that is not. When you run the code, you should only have the “Should see this” available.

Now you could take this a step further and write a converter for IsNotNull. To do this, just simply write another converter but put a != instead. That simple!

Later I will write an article on how to check for specific types of data and to respond appropriate with them.

You will be able to find my example source code here:
https://github.com/ptdave20/ValueConverterExample