Search code examples
c#xamarin.iosmvvmcross

Fluent Bindings and UIButton titles


Since my user interfaces generally need to have localized strings, my view models provide all the strings which the views consume. This includes things like the titles on buttons.

on the iOS side, button titles are set via the SetTitle method.
In order to get a view model string => button title mapping to work, MvvmCross does some magic binding translation to get this to work nicely.

say I have a UIButton named Foo in my view and I want to map its title to a property ButtonLabel in my View Model. In know the following works in order to set up such a binding:

this.AddBindings(new Dictionary<object, string>() {
      {Foo, "Title ButtonTitle"}
 });

Can this same binding be set up using the Fluent Binding system in MvvmCross? I've been reading through the MvvmCross source and I'm not quite getting the binding code.

This following does NOT work (because in reality the button does not have a Title property - it has a SetTitle method):

 var set = this.CreateBindingSet<FooView, FooViewModel>();
 set.Bind(Foo).For(b => b.Title).To(vm => vm.ButtonTitle);
 set.Apply();

Is there another way to achieve the desired result using Fluent Bindings?


Solution

  • Because the button doesn't have a Title propery, then

    set.Bind(Foo).For(b => b.Title).To(vm => vm.ButtonTitle);
    

    will not compile.

    However, the default MvvmCross configuraton for Xamarin.ios has a custom binding defined for UIButton and "Title" - see:

    Because of this you should be able to call:

    set.Bind(Foo).For("Title").To(vm => vm.ButtonTitle);
    

    And this should setup the same binding as:

    this.AddBindings(new Dictionary<object, string>() {
      {Foo, "Title ButtonTitle"}
    });
    

    For a very brief introduction into custom bindings see: https://speakerdeck.com/cirrious/custom-bindings-in-mvvmcross