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

Xamarin Community Toolkit TouchEffect中如何判断被长按的视觉元素?

方案1:直接通过Command参数获取触发元素(最简便)

你现在已经通过SetLongPressCommandParameter给每个按钮设置了参数,只需要改用带参数的Command重载,就能直接拿到传入的参数,进而判断是哪个元素被触发:

如果只需要通过文本区分,代码可以改成:

for (int i = 0; i < choiceButtons.Length; i++)
{
    var currentBtn = choiceButtons[i];
    // 改用带参数的Command,泛型类型和你传入的参数类型一致
    TouchEffect.SetLongPressCommand(currentBtn, new Command<string>(async (textParam) =>
    {
        // textParam就是当前被长按按钮的Text,直接通过它判断是哪个元素
        // 这里也可以直接用currentBtn变量拿到完整的Grid子类实例
    }));
    TouchEffect.SetLongPressCommandParameter(currentBtn, currentBtn.Text);
}

如果需要拿到完整的视觉元素实例,直接把参数改成按钮本身即可:

for (int i = 0; i < choiceButtons.Length; i++)
{
    var currentBtn = choiceButtons[i];
    TouchEffect.SetLongPressCommand(currentBtn, new Command<Grid>(async (targetBtn) =>
    {
        // targetBtn就是被长按的Grid子类实例,可直接访问它的所有属性
    }));
    TouchEffect.SetLongPressCommandParameter(currentBtn, currentBtn);
}

注意:循环内额外声明currentBtn局部变量是为了规避C#旧版本中闭包捕获循环变量的坑,确保每个Command内部拿到的都是当前迭代的元素。


方案2:通过唯一标识匹配

如果你的业务逻辑需要提前和业务数据绑定,可以提前给每个按钮设置Tag、AutomationId等唯一标识属性,传入参数后到数组/字典中匹配对应元素:

// 提前给按钮设置标识
for (int i = 0; i < choiceButtons.Length; i++)
{
    choiceButtons[i].Tag = i; // 比如用索引作为标识
    TouchEffect.SetLongPressCommand(choiceButtons[i], new Command<int>(async (index) =>
    {
        var targetBtn = choiceButtons[index];
        // 后续逻辑
    }));
    TouchEffect.SetLongPressCommandParameter(choiceButtons[i], choiceButtons[i].Tag);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 23:45:04