Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 662
Frank Caico Avatar asked May 25 '13 15:05

Frank Caico


2 Answers

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:

  • https://github.com/slodge/MvvmCross/blob/v3/Cirrious/Cirrious.MvvmCross.Binding.Touch/Target/MvxUIButtonTitleTargetBinding.cs
  • which is registered: https://github.com/slodge/MvvmCross/blob/v3/Cirrious/Cirrious.MvvmCross.Binding.Touch/MvxTouchBindingBuilder.cs#L56

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

like image 185
Stuart Avatar answered Oct 20 '22 00:10

Stuart


In the newer version of MvvmCross 5.x there are strongly typed code based binding properties.

They are done like so:

set.Bind(Button).For(v => v.BindTitle()).To(vm => vm. ButtonTitle);

make sure you add this using:

using MvvmCross.Binding.iOS;

A full list of the extension properties can be found in the documentation here and this is the PR the changes went in on.

like image 39
Iain Smith Avatar answered Oct 20 '22 01:10

Iain Smith