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.
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!
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 }); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With