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( 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
2 Comments
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 ::
Glad you found it helpful!
One Trackback
[…] 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. […]