Attached property for TapGestureRecognizer

Posted on Posted in Xamarin.Forms

While creating Xamarin.Forms applications, definitely you are going to need TapGestureRecognizer often. Implementing it in XAML many times may end up with a lot of unnecessary code. Let’s take a look at that simple clickable Image:

This is a lot of lines, especially when you have to add many clickable controls. However, we can do it better and put everything into a single line using our custom attached property:

Implementation

  • Mark Chipman

    So, how would the “close” command be declared in the xaml codebehind? That’s what I’m missing

    • This can be a default Command in your view model:

      
      public class ViewModel
      {
          public ViewModel()
          {
              this.CloseCommand = new Command(this.OnClose);
          }
      
          public Command CloseCommand { get; set; }
      
          public void OnClose()
          {
              // do something
          }
      }
      

      You can put the same in your code behind, if you don’t use view model. But remember then to set:
      this.BindingContext = this in constructor.

      • Mark Chipman

        Thank you very much.. 🙂