Binding a picker to mvvm command Xamarin forms

theshwaguy picture theshwaguy · Mar 24, 2017 · Viewed 12.5k times · Source

I have been looking everywhere to try and solve this issue, I have not been using Xamarin forms for long but I thought it would have been easy. I am trying to bind a picker selecteditemchanged to a command in the view model, I am using FreshMVVM and Xamarin forms version 2.3.4.214-pre5, I am able to bind the data from the view model but there is no Command option in the picker.

Any help would be appreciated. Thank you

Answer

theshwaguy picture theshwaguy · Mar 24, 2017

I have been able to get a working solution:

First off I installed Xamarin Forms version 2.3.4.214-pre5, it is working just fine. Then with the help of the Xamarin Forum, I was given a solution, which is as-follows:

1 - Install the Behaviors.Forms NuGet package by running Install-Package Behaviors.Forms in the NuGet package manager console.

2 - Then include the following namespace in the XAML page:

<ContentPage xmlns:behaviors="clr-namespace:Behaviors;assembly=Behaviors">
</ContentPage>

3 - Then add the Picker.Behaviors attribute in the Picker tag:

<Picker x:Name="MyPicker"
          ItemsSource="{Binding IdentityProviders}"
          HorizontalOptions="FillAndExpand" Title="Identity Provider"
          Margin="10"
          ItemDisplayBinding="{Binding Description}">
    <Picker.Behaviors>
          <behaviors:EventHandlerBehavior EventName="SelectedIndexChanged">
              <behaviors:InvokeCommandAction Command="{Binding SelectedProviderChanged}" />
          </behaviors:EventHandlerBehavior>
    </Picker.Behaviors>
</Picker>

If you want to pass the data back as a parameter then include the following after the command CommandParameter="{Reference MyPicker}"

That solved my problem, I hope this helps: The help I got was from this post MVVM Light - How to use the selectedIndexChanged event in viewModel