You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin Forms:点击ListView删除按钮如何获取对应商品ID?

解决Xamarin Forms ListView中获取点击项ProductId的问题

嘿,我来帮你搞定这个问题!其实你离正确答案已经很近了,之前尝试的BindingContext思路是对的,只是没做好类型转换而已。下面给你两种简单可靠的方法:

方法一:利用Button的BindingContext(适合当前的Clicked事件写法)

每个ListView项里的控件,它们的BindingContext都是当前绑定的Product对象,所以你可以直接从点击的Button里拿到这个对象,进而获取ProductId:

修改你的后台方法:

void RemoveItemFromShoppingList(object sender, EventArgs e)
{
    // 先把sender转成Button,做空判断避免报错
    var deleteButton = sender as Button;
    if (deleteButton == null) return;

    // 从BindingContext拿到对应的Product实例
    var targetProduct = deleteButton.BindingContext as Product;
    if (targetProduct == null) return;

    // 现在你就能拿到想要的ProductId了!
    int productId = targetProduct.ProductId;

    // 接下来执行你的移除逻辑,比如:
    // ShoppingListItemSource.Remove(targetProduct);
    // 或者根据ProductId去匹配移除,看你的需求
}

这个方法比你之前尝试的通过Parent找Label的方式靠谱多了——要是以后调整Grid的布局(比如增减列),靠索引找控件的代码很容易失效,而BindingContext的方式不受UI结构影响。

方法二:用Command绑定(更符合MVVM模式,推荐长期使用)

如果你的项目是按MVVM架构来的,更推荐用Command代替Clicked事件,这样能把业务逻辑和UI代码解耦:

  1. 首先在你的ViewModel里添加一个移除命令:
using System.Windows.Input;
using Xamarin.Forms;

// 假设你的ViewModel里已经有ShoppingListItemSource集合
public ICommand RemoveItemCommand { get; private set; }

public YourViewModel()
{
    // 初始化命令,泛型参数指定为Product类型
    RemoveItemCommand = new Command<Product>(product =>
    {
        // 直接拿到Product对象,获取ProductId
        int productId = product.ProductId;
        
        // 执行移除操作
        ShoppingListItemSource.Remove(product);
        
        // 这里还可以顺便更新总价Total的绑定值
        UpdateTotalPrice();
    });
}

private void UpdateTotalPrice()
{
    // 计算总价的逻辑,比如:
    Total = ShoppingListItemSource.Sum(p => p.SubTotal);
}
  1. 然后修改XAML里的Button,绑定这个命令:
    首先给你的ContentPage加个名字(方便Command找到ViewModel):
<ContentPage x:Name="ShoppingCartPage" ...>

然后修改Button的代码:

<Button Grid.Column="6" Grid.Row="2" VerticalOptions="Start" Text="Delete" 
        Command="{Binding BindingContext.RemoveItemCommand, Source={x:Reference ShoppingCartPage}}"
        CommandParameter="{Binding .}" />

这里CommandParameter="{Binding .}"是把当前项的Product对象作为参数传给Command,这样ViewModel里直接就能拿到要删除的商品。

这两种方法都能完美解决你的问题,选哪种看你当前的代码架构就行~

内容的提问来源于stack exchange,提问作者John

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 12:47:28