Agat
Agat

Reputation: 4779

MvvmCross: GestureRecognized binding to ViewModel action

There is such ability to bind buttons actions directly like this:

var set = this.CreateBindingSet<...
set.Bind(button).To(x => x.Go);

but what's about UITapGestureRecognizer, for instance. How should I bind it (it's tap action) in such elegant way?

Thank you!

Upvotes: 7

Views: 3850

Answers (2)

xleon
xleon

Reputation: 6365

Just for reference. Newer version of MvvMcross includes a UIView method extension (see MvxTapGestureRecognizerBehaviour) out of the box that you can use to bind the tap gesture:

using Cirrious.MvvmCross.Binding.Touch.Views.Gestures;

// in this case "Photo" is an MvxImageView
set.Bind(Photo.Tap()).For(tap => tap.Command).To("OpenImage");

Upvotes: 21

Stuart
Stuart

Reputation: 66882

You could add this yourself if you wanted to.

e.g. something like

  public class TapBehaviour
  {
      public ICommand Command { get;set; }

      public TapBehaviour(UIView view)
      {
          var tap = new UITapGestureRecognizer(() => 
          {
              var command = Command;
              if (command != null)
                   command.Execute(null);
          });
          view.AddGestureRecognizer(tap);
      }
  }

  public static class BehaviourExtensions
  {
      public static TapBehaviour Tap(this UIView view)
      {
          return new TapBehaviour(view);
      }
  }

  // binding
  set.Bind(label.Tap()).For(tap => tap.Command).To(x => x.Go);

I think that would work - but this is coding live here!


Advanced> If you wanted to, you could also remove the need for the For(tap => tap.Command) part by registering a default binding property for TapBehaviour - to do this override Setup.FillBindingNames and use:

  registry.AddOrOverwrite(typeof (TapBehaviour), "Command");

After this, then the binding could be:

  set.Bind(label.Tap()).To(x => x.Go);

Upvotes: 18

Related Questions