XAML 使用MAUI MVVM点击或触摸列表中的一个项目时,如何获得点击命令?

ivqmmu1c  于 2023-01-10  发布在  其他
关注(0)|答案(1)|浏览(250)

我很难找到一种方法来做到这一点,它已经3天了,我不能弄清楚。我只是想找到一种方法,当我点击或点击列表中的任何项目,我想激发一个命令或方法,以便我可以写我的代码。

    • 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>

使用CommunityToolkit的MVVM代码隐藏. 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
        }

    }
    • 库存. cs**
public partial class Inventario : ContentPage
{
    public Inventario(InventarioViewModel vm)
    {
        BindingContext = vm;
        InitializeComponent();

    }
    
    private void ListView_ItemTapped(object sender, ItemTappedEventArgs e)
    {
        
    }

}

我的方式不起作用。所有我正在寻找的只是ItemTapped()被解雇后,点击或选择列表中的任何项目,但我还需要捕捉产品信息点击。
我试着这样说:

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

但是说xaml错误:
在ListView中找不到属性ItemTappedCommand。

vkc1a9a2

vkc1a9a21#

首先,保留对虚拟机的引用

InventarioViewModel VM;

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

然后在事件处理程序中,您可以调用VM上的方法或命令(您需要将ItemTapped设置为public)

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

相关问题