Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind Picker in Xamarin.Forms

Tags:

mvvm

xamarin

So I've been wanting to bind the items of two pickers in Xamarin.Forms to my ViewModel. I have mainly used binding for textfields, where I just write something like:

<Label Text="{Binding CurrentDate}" />

and simply by setting the binding context, defining a property in the viewmodel

    public System.DateTime CurrentDate{
        get { return currentDate; }
        set { currentDate = value; PropertyChanged(this, new PropertyChangedEventArgs("CurrentDate")); }
    }

I am done binding. Now I have two pickers. The pickers represent a map/dictionary. Dictionary>. "A" is mapped to {"1","2"} and "B" is mapped to {"4","5"}. The first picker should show "A" and "B" as options. The second one should display the values associated with the chosen value from the first picker.

So there are two questions. 1) How do I bind a picker? 2) How do I bind a picker that has data that depends on another pickers selection?

I tried

<Picker Items="{Binding ItemsA}"></Picker>

With a matching property

    public List<string> ItemsA
    {
        get { return itemsA;}
        set { itemsA = value;PropertyChanged(this, new PropertyChangedEventArgs("ItemsA")); }
    }

Am I missing out on something here? Help would be appreciated.

like image 962
why_vincent Avatar asked Jan 25 '26 09:01

why_vincent


1 Answers

This functionality is unfortunately missing from the standard component, but relatively easy to add as detailed at https://forums.xamarin.com/discussion/30801/xamarin-forms-bindable-picker. Using this derived component you will then be able to bind ItemsSource and SelectedItem properties. It's also relatively easy to add WPF-like DisplayMemberPath and ValueMemberPath properties if required.

like image 161
Ben Jackson Avatar answered Jan 27 '26 00:01

Ben Jackson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!