Search code examples
data-bindingmvvmcross

Fluent binding and conversions


When following the Tutorial for TipCalc's iOS UI, I noticed that the binding method described is obsolete(?) and decided to start using Fluent bindings like described here.

Everything gone fine except for one thing: the iOS slider on the tutorial uses a float value between 0 and 1, and the view model uses a int between 0 and 100. So, obviously, I need a conversion here.

Since it's a two-way-binding, how can bind it to be converted for ViewModel -> View and View -> ViewModel? (ideally with fluent binding)

Also, I'd like to know how can I register a conversion under a "name" to later reuse it. Like it seems to be done on this line.

I tried to search on MvvmCross repos for these named conversions but I didn't find anything like a list of the available conversions, there is such a thing?

Thanks a lot for any help!!


Solution

  • I noticed that the binding method described is obsolete(?)

    The message attached to that method is:

       [Obsolete("Please use SourceDescribed or FullyDescribed instead")]
    

    So use SourceDescribed if you only want to describe the source, or FullyDescribed if you want to describe the source and target.

       set.Bind(label).For(l => l.Text).SourceDescribed("'Hello ' + SourceText");
    

    or:

       set.Bind(label).FullyDescribed("Text 'Hello ' + SourceText");
    

    Since it's a two-way-binding, how can bind it to be converted for ViewModel -> View and View -> ViewModel?

    Two way converters implement both Convert and ConvertBack.

    For example - see:

    public class TwoWayConverter : MvxValueConverter<double, string>
    {
        protected override string Convert(double value, Type targetType, object parameter, CultureInfo culture)
        {
            return (value*value).ToString();
        }
    
        protected override double ConvertBack(string value, Type targetType, object parameter, CultureInfo culture)
        {
            double doubleValue;
            double.TryParse(value, out doubleValue);
            return Math.Sqrt(doubleValue);
        }
    }
    

    from https://github.com/MvvmCross/MvvmCross-Tutorials/blob/master/ValueConversion/ValueConversion.Core/Converters/Converters.cs

    I'd like to know how can I register a conversion under a "name" to later reuse it

    The names are registered by reflection and convention - see a full description in https://github.com/MvvmCross/MvvmCross/wiki/Value-Converters#referencing-value-converters-in-touch-and-droid

    a list of the available conversions

    MvvmCross doesn't provide many by default - these are mainly app things.

    The only built-in converters that I know of are for:

    • color
    • visible
    • language
    • command parameter

    All of these are discussed in https://github.com/MvvmCross/MvvmCross/wiki/Value-Converters#the-mvx-visibility-valueconverters