Something I needed to do in a recent Xamarin.Forms project was to create a subclass of Image that had a custom ‘Clicked’ event handler attached. In other words, I simply wanted to be able to set Clicked=”MyHandler” in the XAML description of the image and have MyMethod called when the image was clicked – much the same as the Xamarin.Forms.Button class currently works.
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); } } } }
These articles can take a lot of time and effort to put together. If you found this useful and would like to help me create more content like this like you can support me below – I really appreciate it!