Creating Bindable Properties in Xamarin.Forms

Something you’re bound to run into sooner or later when developing with Xamarin.Forms is the issue of how to make a property bindable. Fortunately it’s pretty easy to do – though I found it hard to find a simple example online that worked both for setting the property programmatically and via xaml.

So, without further ado here’s an example of a bindable ‘Foobar’ property that can be set both programmatically and via xaml. Just copy/paste this into your own code whilst changing the relevant bits and you should be fine…

Note: ‘YourClass’ should be replaced by the type name of the class that holds the property. References to ‘bool’ should (obviously) replaced by the type of property you are declaring. The ‘false’ value that is passed to the BindableProperty.Create() method refers to the default value for the property and should be replace by something meaningful.

public static readonly BindableProperty FoobarProperty=BindableProperty.Create<YourClass,bool>( p => p.Foobar, false );

public bool Foobar
{
	get 
	{ 
		return (bool)GetValue(FoobarProperty); 
	}
	set 
	{
		SetValue(FoobarProperty, value); 
	}
}

private void UpdateFoobar()
{
	// 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
	// so if you need to reference the old value you will
	// need to store it in a class variable
}

protected override void OnPropertyChanged(string propertyName)
{
	base.OnPropertyChanged(propertyName);

	switch( propertyName )
	{
		case "Foobar":
			UpdateFoobar();
			break;
	}
}

Hopefully that’s been helpful – now why not take a brief break from work to watch our trailer for ‘Attack Of Giant Jumping Man’…


Attack of Giant Jumping Man
Advertisements

2 Comments

  1. Joe
    Posted December 10, 2015 at 7:53 pm | Permalink | Reply

    Great snippet! You’re right: it’s sort of difficult to find a concise well-crafted example of a custom binding out there. This one is good. :: yoink ::

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: