Xamarin.Forms ListView点击项时如何获取ObservableCollection对应Value值
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
Itemproperty returns anobject, so we use C#'s pattern matching (isexpression) to safely cast it toSettings—this avoids null reference errors if the item is ever null. - If you were using the
ItemSelectedevent instead, it usesSelectedItemChangedEventArgs, and you'd access theSelectedItemproperty 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

