Fluent Bindings and UIButton titles
Asked Answered
G

2

13

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?

Galangal answered 25/5, 2013 at 15:23 Comment(0)
C
27

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

Chausses answered 25/5, 2013 at 15:28 Comment(3)
For localised strings, you might also want to consider the localised language binding functionality - see speakerdeck.com/cirrious/internationalization-in-mvvmcross and slodge.blogspot.co.uk/2013/05/…Chausses
Thats awesome. You've answered my question and several others I had without even asking.Galangal
Stuart also mentioned: "if you look at this link then you'll see how we add a 'SpecialProperty' binding property and a 'HitThis' binding property to the system"Galangal
F
6

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.

Florenceflorencia answered 27/9, 2017 at 10:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.