Tag Archives: mvvm

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!

Advertisements