Search code examples
c#xamlmvvmmaui

How to get Tapped Command when clicking or touching an item in the List using MAUI MVVM?


I am having a hard time finding a way how to do this and its been 3 days and I cant figure it out. I am just trying to find a way when I click or tap any item in the list I want to fire a Command or Method so I can write my code.

XAML

<ListView ItemsSource="{Binding Productos}" HasUnevenRows="True" SelectedItem="{Binding SelectedItem}" IsPullToRefreshEnabled="True" 
          RefreshCommand="{Binding RefreshCommand}" IsRefreshing="{Binding IsRefreshLoading}" ItemTapped="{Binding ItemTappedCommand}">
        <ListView.ItemTemplate>
                <!-- ... -->
        </ListView.ItemTemplate>
</ListView>

Code behind with MVVM using CommunityToolkit.Mvvm

using CommunityToolkit.Mvvm.Input;

public partial class InventarioViewModel : ObservableObject
{
    // prods
    [ObservableProperty]
    List<Productos> _productos = new List<Productos>();
    
    [ObservableProperty]
    private Productos _selectedItem;
    
    [ObservableProperty]
    private bool _isRefreshLoading = false;
    
    public InventarioViewModel(ILoginService loginService)
    {
        _loginService = loginService;
    
        Task.Run(async () => { await CargarProductos(); });      
    }  
    
    private async Task CargarProductos()
    {
        // code for loading products
    }         
    
    // here is here i wanna trigger when I click or tap any item
    // in the list but i cannot make this work
    [RelayCommand]
    void ItemTapped()
    {
        // Handle the ItemTapped event here
    }
}

Inventario.cs

public partial class Inventario : ContentPage
{
    public Inventario(InventarioViewModel vm)
    {
        BindingContext = vm;
        InitializeComponent();
    }
        
    private void ListView_ItemTapped(object sender, ItemTappedEventArgs e)
    {
    }
}

The way I have does not work. All I am looking is just ItemTapped() to be fired after clicking or selecting any item in the list but I also need to capture the Product information tapped.

I tried this way:

<ListView ItemTappedCommand="{Binding ItemTappedCommand}"></ListView>

but says xaml error :

The property ItemTappedCommand was not found in ListView.


Solution

  • first, keep a reference to your VM

    InventarioViewModel VM;
    
    public Inventario(InventarioViewModel vm)
    {
        InitializeComponent();
        BindingContext = ViewModel = vm;
    }
    

    then in your event handler you can call a method or command on your VM (you will need to make ItemTapped public)

    private void ListView_ItemTapped(object sender, ItemTappedEventArgs e)
    {
        VM.ItemTapped(...);
    }