Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin Forms ListView ItemTapped/ItemSelected Command Binding on XAML

Tags:

How can I bind a ICommand object from my ViewModel (currently in BindingContext) to the ItemTapped or ItemSelected from a ListView in XAML?

This is a simple task when using a Button, I just set Command="MyViewModelCommand" and everything works.

like image 477
MarcioGomes Avatar asked Jul 17 '14 00:07

MarcioGomes


2 Answers

I am not sure why you need to give Item Selected or Item Tapped event in your page when you can directly get the selected / tapped object directly in your ViewModel:

I think you've bind the listview with below types of code

<ListView ItemsSource="{Binding PermitDetails}"  SelectedItem="{Binding objItemSelected, Mode=TwoWay}" x:Name="lst"  RowHeight="35" HorizontalOptions="FillAndExpand"  VerticalOptions="Fill"> 

And in the View Model which you've bind with the page, you've to define the property objItemSelected as mentioned in below code

private Permit _ItemSelected; public Permit objItemSelected {     get {         return _ItemSelected;     }     set {         if (_ItemSelected != value) {             _ItemSelected = value;             OnPropertyChanged ("ItemSelected");         }     } } 

And if you want to perform any additional functionality like navigating to detail page, you can do it from the set property after OnPropertyChanged statement is executed.

Hope this helps!

like image 149
Nirav Mehta Avatar answered Sep 18 '22 22:09

Nirav Mehta


This is an old question, and maybe this is a fairly recent development, but you can use the Behaviors on any control to convert an event into an ICommand.

An example...

<ListView ItemsSource="{Binding Tags}"             SelectedItem="{Binding SelectedTag}">     <ListView.Behaviors>         <behaviors:EventHandlerBehavior EventName="ItemSelected">             <behaviors:InvokeCommandAction Command="{Binding SelectedTagChanged}" />         </behaviors:EventHandlerBehavior>     </ListView.Behaviors>     <ListView.ItemTemplate>         <DataTemplate>             <ViewCell>                 <ContentView Padding="8">                     <Label Text="{Binding DisplayValue}" />                 </ContentView>             </ViewCell>         </DataTemplate>     </ListView.ItemTemplate> </ListView> 

In this example, the ItemSelected event will map to the SelectedTagChanged command in your view model which looks like this...

public Command SelectedTagChanged {     get     {         return new Command(row =>         {             // do something         });     } } 
like image 21
John Livermore Avatar answered Sep 17 '22 22:09

John Livermore