Forum Xamarin.iOS

MVVMLight value converter for Xamairn.IOS


Does anyone have an example of how to implement a simple binding value converter (e.g. int to float.) in a Xamarin.IOS environment?
From what I can see, the iValueConverter interface is not a part of the MVVMLight package. E.g. Xamarin.Forms has iValueConverter integrated and MVVMCross has its own implementation which is MvxValueConverter. So I'm wondering how I can create my own binding converters in a MVVMLight enabled Xamarin IOS project (Mac).
I found a Nuget package (Alfa.Common) which implements some general converters. Unfortunately, it doesn't cover the ones I was looking for. So if anyone knows where I can find an example which shows how to do it, I would be thrilled.

Thanks in advance.



  • RameshDRameshD INMember ✭✭

    I know this is an old post, but for someone like me who comes looking for this, here's what you need:

    In MVVMLight for Xamarin Android and iOS, we cannot use an IValueConverter implementation (because it is not available). But we don't need to, because MVVMLight accepts a simple Func<TSource, TTarget> for performing conversions. For the int to float conversion example from above, we need to provide a function of type Func<int, float> to a method called ConvertSourceToTarget that is available in the Binding class. Reverse conversions are performed by providing a similar function to a method called ConvertTargetToSource.


    Binding b = this.SetBinding( vm => vm.IntProperty, view, view => view.FloatProperty, BindingMode.TwoWay );
    b.ConvertSourceToTarget( intProperty => {
        return (float)intProperty;
    } );
    b.ConvertTargetToSource( floatProperty => {
        return (int)floatProperty;
    } );

    Or, using the fluent version:

    Binding b = this.SetBinding( vm => vm.IntProperty, view, view => view.FloatProperty, BindingMode.TwoWay )
        .ConvertSourceToTarget( intProperty => {
            return (float)intProperty;
        } )
        .ConvertTargetToSource( floatProperty => {
            return (int)floatProperty;
        } );

    There are no ConverterParameters either. It would've been nice if ConvertSourceToTarget and its counterpart took a parameter of type Func<TSource, TParam, TTarget> and an object of type TParam to use during the conversions. For now, I use a static class with static fields and the converter methods to get around this limitation. Gets the job done. :wink:

    I have tested this on Xamarin Android, but it should work the same on iOS too.

    Hope this helps someone.

Sign In or Register to comment.