Implementing Converters Returning Native Types in MvvmCross

February 24th 2014 MvvmCross

Although MvvmCross allows creating portable converters which can be used on multiple different platforms, they can still only return types which are also portable. Of course there are cases when it is desirable for a converter to return non-portable classes such as Visibility, Brush or BitmapImage on Windows platforms.

The basics are probably already covered by MvvmCross itself; it includes visibility and color converters which can be used on all platforms. Still, there will always be other native classes you will need. In this case the best approach is to implement a base portable class returning a common portable value which can be converted to specific native values in a simple manner. For a BitmapImage such a common value could be a Url.

On Windows platforms native converters always need to be wrapped in a MvxNativeValueConverter, anyway. That same wrapper can also take care of the above mentioned simple type conversion. This would be an example for BitmapImage:

public class ImageConverter :
    MvxNativeValueConverter<MvxConverters.UriConverter>
{
    public override object Convert(object value, Type targetType,
                                   object parameter, CultureInfo culture)
    {
        var uri =  base.Convert(value, targetType, parameter, culture) as Uri;
        return uri == null ? null : new BitmapImage(uri);
    }
}

This way all actual business logic is kept in the portable converter, allowing it to be reused and tested centrally. The native wrappers are just trivial type converters.

Get notified when a new blog post is published (usually every Friday):

If you're looking for online one-on-one mentorship on a related topic, you can find me on Codementor.
If you need a team of experienced software engineers to help you with a project, contact us at Razum.
Copyright
Creative Commons License