Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin Forms - How to get the index number from ListView SelectedItem

I am completely stuck on this. I have a ListView defined in XAML code, but I need to find out what the int of the selected item I am tapping.

My listview is called PeopleList When I tap on a cell I need to get the index number of that cell.

So I can do PeopleList.SelectedItem but this returns an object - not an int.

I have tried parsing it and converting and everything that makes logically sense to me.

Can someone please tell me how to get the int for the selectedItem?

like image 280
jwknz Avatar asked Dec 23 '22 18:12

jwknz


1 Answers

In the event handler for your ItemTapped event, do the following:

private void Handle_ItemTapped (object sender, Xamarin.Forms.ItemTappedEventArgs e)
{
    var index = (myListView.ItemsSource as List<Person>).IndexOf (e.SelectedItem as Person);
}

Make sure the type of the collection is right. This isn't the most elegant way, but it works.

like image 173
Gerald Versluis Avatar answered Jan 09 '23 00:01

Gerald Versluis