6
votes

The Xamarin Forms doc Xamarin.Forms.Picker.SelectedItem says there is a public property SelectedItem for Picker. However, I get an error when I try to bind to it. The picker is not very useful if you have to manually handle the SelectedIndex property.

Tony

2
Which version of Xamarin.Forms are you using? Bindable picker exists in 2.3.4 onlyMikalai Daronin
Make sure that the type of VM property used to bind to SelectedItem is same as that of the type used in ItemsSource collection.Sharada Gururaj

2 Answers

8
votes

No need to manually handle the SelectedIndex. You can use the Picker's SelectedItem property. Just make sure your types are the same. For example, if your ItemsSource is bound to a property:

BookTitles List<string> { get; set; }

your SelectedItem has to be something like:

SelectedBookTitle string { get; set; }

Make sure to set the SelectedBookTitle value to show a title when the page is first shown. Do not forget to set Mode to TwoWay on the SelectedItem Binding. for example:

<Picker ItemsSource="{Binding BookTitles}" SelectedItem="{Binding 
SelectedBookTitle, Mode=TwoWay}" />

This will ensure the title is shown when the page is first displayed, and keeps the value of SelectedBookTitle equal on the Page and codebehind/viewmodel.

No need to use behaviours in this example.

3
votes

You can add this feature relatively easy, even with older versions of Forms pre 2.3.4 which supports it out of the box. Just create a custom behaviour to bind the picker items. You can implement your own version or use an existing library, like the Xamarin University Infrastructure Library which is available as source and as a Nuget

The detailed documentation shows how to use it:

<Picker ...>
   <Picker.Behaviors>
      <inf:PickerBindBehavior Items="{Binding Colors}" 
                          SelectedItem="{Binding FavoriteColor}" />
   </Picker.Behaviors>
</Picker>

The approach of the behaviour is to expose a bindable property (the items) and use an observable collection. Whenever that changes, the behaviour updates the items of the picker.