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

.NET Maui:如何从CollectionView内优雅获取点击事件对应的Shipment对象

几种简洁优雅的实现方式

方案1:直接读取Frame的BindingContext(最省心)

你的Frame本身就绑定了Shipment对象,它的BindingContext就是你要的实例,完全不用绕手势识别器:

private void OnFrameClick(object sender, EventArgs e)
{
    var shipment = ((Frame)sender).BindingContext as Shipment;
    if (shipment is not null)
    {
        // 在这里处理业务逻辑
    }
}

方案2:用TappedEventArgs的Parameter属性

你之前注释的e.Parameter其实才是正确路径——CommandParameter会直接传到事件参数里,不用去遍历手势集合:

private void OnFrameClick(object sender, EventArgs e)
{
    var shipment = (e as TappedEventArgs)?.Parameter as Shipment;
    if (shipment is not null)
    {
        // 处理逻辑
    }
}

XAML不需要改动,这种写法比你原来的代码少了一堆中间变量,还通过空传播运算符避免了空引用异常。

方案3:MVVM风格的命令绑定(规范推荐)

如果项目遵循MVVM模式,用命令绑定更解耦,把业务逻辑放到ViewModel中:

  1. 在ViewModel里定义命令:
public ICommand FrameTappedCommand { get; }

// 构造函数中初始化命令
public YourViewModel()
{
    FrameTappedCommand = new Command<Shipment>(HandleFrameTapped);
}

private void HandleFrameTapped(Shipment shipment)
{
    // 直接拿到Shipment对象处理逻辑
}
  1. 修改XAML中的TapGestureRecognizer:
<TapGestureRecognizer Command="{Binding Source={RelativeSource AncestorType={x:Type local:YourViewModel}}, Path=FrameTappedCommand}"
                      CommandParameter="{Binding .}"
                      NumberOfTapsRequired="1" />

这种方式完全脱离代码后台,符合.NET Maui的最佳实践。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 16:52:35