Monthly Archives: August 2018

Creating Custom “Clicked” Event Handlers in Xamarin.Forms

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!

Buy Me a Coffee at ko-fi.com

Creating Bindable Properties in Xamarin.Forms v3.0+

This is an updated version of what has proven to be one of the most popular posts on this site – a simple ‘cut and paste’ solution to create custom bindable properties in Xamarin.Forms. The original post can be found here.

Unlike many other online examples, this one allows you to set the property both programmatically and via XAML. I’ve updated the code to make it more ‘cut,paste,search,replace’ friendly and to get rid of the generic types which will be deprecated in future versions of Xamarin.Forms.

A lambda expression is used to route the PropertyChanged call back to the originating object – generally I’ve found this approach more useful than a static callback. Please excuse the gratuitous casting!

To use simply replace MyClass with the name of your containing class (which will be a subclass of BindableObject), FooBar with the name of your property, and the references to bool to the type of your property.

Hopefully the inline comments make the code self-explanatory. If you run into any problems or just find this useful please leave a comment!

#region foobarproperty
// Creates the bindable property using a lambda expression to route the PropertyChanged 
// handler back to the containing class
public static readonly BindableProperty FooBarProperty = BindableProperty.Create(   
    nameof(FooBar), 	// The name of the property you are creating
    typeof(bool), 	// The type of the property you are creating
    typeof(MyClass), 	// The type of your containing class
    false, 		// The default value of the property you are creating
    propertyChanged: (BindableObject bindable, object old_value, object new_value) => 
    {
    	((MyClass)bindable).UpdateFooBar((bool)old_value, (bool)new_value);
    });

/// Used to set your property programatically
public bool FooBar
{
    get
    {
        return (bool)GetValue(FooBarProperty);
    }
    set
    {
        SetValue(FooBarProperty, value);
    }
}

/// Called when the value of your property has been updated
/// 
/// Note that this method is only called when the property has CHANGED, not
/// if it has been set to the same value - take not of the default value!
private void UpdateFooBar( bool old_value, bool new_value )
{
    // Do whatever you need to do when the property 
    // has been set here. By the time this method is
    // called FooBar will already hold the updated value
}
#endregion

If you found this helpful I always appreciate more followers on Twitter!