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

.NET MAUI:如何将CollectionView项索引传递给RemoveEquipmentCommand

解决CollectionView删除按钮传递参数的问题

你可以通过两种方式实现删除功能,更推荐直接传递当前项对象,无需依赖索引:

方案一:传递当前EquipmentDetails对象(推荐)

首先修正按钮的命令绑定,让它指向父ViewModel的RemoveEquipmentCommand,并把当前项作为参数传递:

修改XAML中的按钮代码:

<Button Text="x"
        BackgroundColor="Red"
        Grid.Column="1"
        Command="{Binding Source={RelativeSource AncestorType={x:Type viewModel:AddLogEntryViewModel}}, Path=RemoveEquipmentCommand}"
        CommandParameter="{Binding .}" />

然后在AddLogEntryViewModel中实现命令逻辑,直接移除传入的项:

// 定义命令
public ICommand RemoveEquipmentCommand => new Command<EquipmentDetails>(RemoveEquipment);

private void RemoveEquipment(EquipmentDetails targetEquipment)
{
    if (targetEquipment != null && NewLogEntry.EquipmentDetails.Contains(targetEquipment))
    {
        NewLogEntry.EquipmentDetails.Remove(targetEquipment);
    }
}

方案二:传递项的索引(若确实需要)

如果必须使用索引,你可以通过绑定获取当前项在CollectionView中的索引,再传递给命令:

修改按钮的CommandParameter:

<Button Text="x"
        BackgroundColor="Red"
        Grid.Column="1"
        Command="{Binding Source={RelativeSource AncestorType={x:Type viewModel:AddLogEntryViewModel}}, Path=RemoveEquipmentCommand}"
        CommandParameter="{Binding Source={RelativeSource AncestorType={x:Type CollectionViewItem}}, Path=Index}" />

然后ViewModel中处理索引移除:

public ICommand RemoveEquipmentCommand => new Command<int>(RemoveEquipmentByIndex);

private void RemoveEquipmentByIndex(int index)
{
    if (index >= 0 && index < NewLogEntry.EquipmentDetails.Count)
    {
        NewLogEntry.EquipmentDetails.RemoveAt(index);
    }
}

注意事项

  • 确保你的NewLogEntry.EquipmentDetails是可观察集合(ObservableCollection<EquipmentDetails>),这样删除项后CollectionView才能自动更新UI。
  • 方案一无需维护索引,逻辑更简洁,避免集合变化时索引错位的问题,优先推荐。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 05:48:05