Search code examples
iphoneiosxamarinmvvmcrossuitapgesturerecognizer

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!


Solution

  • 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);