Xamarin, Binding, enums and IValueConverter: how to improve your XAML.

Sometimes we need to show a custom value in our XAML and this operation is not always immediate but with this tutorial you’ll discover how easy it is.

Let’s say that in our photo app we have a setting for the size of our photo. We store this setting as an integer but of course we want to show a better information to the user. Let’s say that

  • 0: Small
  • 1:Medium
  • 2: Large
  • 3: Full Size

This is what we want to achieve (Image Size):

A first idea could be to add a label with a simple text and to change the text from the code behind. Something like this:

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

But we are better developers than that so we want to use an integer and a Converter:


<Label  Text="{Binding ImageSize, StringFormat='Image Size ({0})', Converter={StaticResource IntToImageSizeConverter}}"/>

As you have seen, instead of using a text, here we use our integer value, a converter and a StringFormat to format our text.

In our converter we receive an integer value and we return an element of the PhotoSize enum. This is the source code of the converter:

IValueConverter implementation public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is int b)
            {
                switch (b)
                {
                    case 0: return PhotoSize.Small;
                    case 1: return PhotoSize.Medium;
                    case 2: return PhotoSize.Large;
                    case 3: return PhotoSize.Full;
                }
            }

            return value;
        }

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

The latest thing to do is to register the converter in our dictionary:

<helpers:IntToImageSizeConverter x:Key="IntToImageSizeConverter"/>

With this code we can use our integer variable to show a more meaningful text. Easy. Isn’t it?

If you want to know more or you need more info, write a comment here. If you liked the article share it!