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

Xamarin.Forms ListView点击项时如何获取ObservableCollection对应Value值

How to Display the Corresponding Value When Tapping a ListView Item

First, let's clear up your confusion: System.EventArgs is not a namespace—it's a base event argument class that lives in the System namespace. Most event args types inherit from it, but the ListView.ItemTapped event in Xamarin.Forms uses a specific derived type: ItemTappedEventArgs, which includes the Item property you need to access the tapped data object.

Here's how to fix your code:

1. Update the event method's parameter type

Change your MyItemTapped method's second parameter from System.EventArgs e to ItemTappedEventArgs e. This lets you access the tapped item:

void MyItemTapped(object sender, ItemTappedEventArgs e)
{
    // Safely check and cast the tapped item to your Settings type
    if (e.Item is Settings tappedSetting)
    {
        DisplayAlert("Corresponding Value", tappedSetting.Value, "OK");
    }
}

2. Verify the namespace reference

If your code file doesn't already have it, add this using directive at the top to access ItemTappedEventArgs:

using Xamarin.Forms;

Extra notes:

  • The Item property returns an object, so we use C#'s pattern matching (is expression) to safely cast it to Settings—this avoids null reference errors if the item is ever null.
  • If you were using the ItemSelected event instead, it uses SelectedItemChangedEventArgs, and you'd access the SelectedItem property to get the selected object (the same casting logic applies).

After making these changes, when a user taps the "Meaning of Life" list item, an alert will pop up showing its corresponding value: "42".

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:41:32