Whilst I was used to catching touch events using TapGestureRecognizer, the syntax for setting up a custom event handler that could be set from XAML eluded me for quite some time and, as it was tough to find any decent examples online, I decided to create my own.
So here’s a simple ClickableImage subclass of Image with a custom Clicked handler added. The code is extremely straightforward so you could very easily copy and paste to create a similar ClickableLabel subclass of Label, or a custom ContentView, or whatever…
using System; using Xamarin.Forms; namespace Com.Bitbull.Examples { public class ClickableImage:Image { // This is the event handler that will be set from your XAML public event EventHandler Clicked; public ClickableImage() { // Set up a gesture recognizer to respond to touch events TapGestureRecognizer tap = new TapGestureRecognizer(); tap.Command = new Command(OnClicked); GestureRecognizers.Add(tap); } // Called every time the image is clicked public void OnClicked(object sender) { if (Clicked != null) { // Call the custom event handler (assuming one has been set) // // You could always subclass EventArgs to send something more useful than // EventArgs.Empty here but more often than not that's not necessary this.Clicked(this, EventArgs.Empty); } } } }