Xamarin, MvvmCross and ValueConverters

This post will show you how to use ValueConverters in an Android app built with Xamarin. For an introduction to Xamarin and MvvmCross read this blog post.

If you want to convert values before you bind it to a property you can use value converters. For example if you want to view an element if a string property is not null you can use a value converter to convert it to a boolean.

First you will create a new class that inherit from MvxValueConverter and then override the Convert method and write your code there, in this case a simple null check. The class has to name end with ValueConverter.

public class IsNullValueConverter : MvxValueConverter
    public override object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
          return !String.IsNullOrEmpty(value as string);

Then name of the value converter will be the first part of the class name, so my IsNullValueConverter class will be used as IsNull in the Android Xml and the argument will be the property in your view model that you want to use.

ValueConverters is a very effective and simple way to do convert values without to create a property in the ViewModel for it.

  8/4/2014 - 11:03 AM