How to add a custom Bindable Property to Xamarin.Forms control

Hi Guys,

Today, I am going to teach you about adding custom Bindable properties to Built in controls in Xamarin.Forms.

Recently, I have got a requirement to create a Picker with ItemsSource property. The underline idea was to use MVVM model with Picker contols. In other words, the developer wanted to bind his List object as a property from ViewModel class to XAML binding on the Page. Its a really solid way of organizing the code. In fact, the MVVM is the most recommended and standard approach when comes to the World of Xamarin.

But unfortunately,  the Picker control doesn’t have a ItemsSource property by defaluty. But controls like ListView does.

Ok. here is the solution, what I have given to that developer…

Create a Custom Picker with ItemsSource Bindable property.

  1. Create your custom picker class

using System.Collections.Generic;
using Xamarin.Forms;

namespace FDNet
{
    public class OutletPicker : Picker
    {
        public static readonly BindableProperty ItemSourceProperty = BindableProperty.Create(nameof(ItemSource), typeof(List<string>), typeof(OutletPicker), null);

        public List<string> ItemSource
        {
            get
            {
                return (List<string>)GetValue(ItemSourceProperty);
            }
            set
            {
                SetValue(ItemSourceProperty, value);
            }
        }

        protected override void OnPropertyChanged(string propertyName = null)
        {
            base.OnPropertyChanged(propertyName);
            if (propertyName == nameof(ItemSource))
            {
                this.Items.Clear();
                if (ItemSource != null)
                {
                    foreach (var item in ItemSource)
                    {
                        this.Items.Add(item);
                    }
                }
            }
        }
    }
}

2. Add XAML reference variable to the Page.

xmlns:local=clrnamespace:FDNet;assembly=FDNet

3. Add the control and bind the property.

<local:OutletPicker Title=Select ItemSource={Binding Outlets} HorizontalOptions=Center WidthRequest=300 />

Now you can see our custom bindable property   ItemSource={Binding Outlets})

4. Demo.

Outlets = new List<string> { 4G LTE, 4G Broadband, Fiber connection };

<local:OutletPicker Title=Select ItemSource={Binding Outlets} HorizontalOptions=Center WidthRequest=300 />

select

Ok Guys…

Happy coding… 🙂

One thought on “How to add a custom Bindable Property to Xamarin.Forms control

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