Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding a picker to mvvm command Xamarin forms

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

like image 210
theshwaguy Avatar asked Mar 24 '17 16:03

theshwaguy


People also ask

How does binding work in Xamarin forms?

Data binding is the technique of linking properties of two objects so that changes in one property are automatically reflected in the other property. Data binding is an integral part of the Model-View-ViewModel (MVVM) application architecture.

What is MVVM pattern in Xamarin forms?

The MVVM pattern enforces a separation between three software layers — the XAML user interface, called the View; the underlying data, called the Model; and an intermediary between the View and the Model, called the ViewModel.


1 Answers

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

like image 149
theshwaguy Avatar answered Sep 20 '22 09:09

theshwaguy