why_vincent
why_vincent

Reputation: 2262

How to bind Picker in Xamarin.Forms

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.

Upvotes: 3

Views: 12046

Answers (2)

deadlydog
deadlydog

Reputation: 24384

Looks like this functionality is built into the regular Xamarin.Forms Picker now. It is currently in the pre-release NuGet package for version 2.3.4-pre1, but should be in the stable 2.3.4+ versions once it is released. Instead of binding to Items you bind to ItemsSource and SelectedItem.

Upvotes: 4

Ben Jackson
Ben Jackson

Reputation: 1138

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.

Upvotes: 4

Related Questions