Tony Lugg
Tony Lugg

Reputation: 572

Xamarin Forms Picker SelectedItem Binding

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

Upvotes: 8

Views: 18785

Answers (2)

Daniel Bikker
Daniel Bikker

Reputation: 111

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.

Upvotes: 11

Krumelur
Krumelur

Reputation: 33048

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.

Upvotes: 4

Related Questions