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

jwknz picture jwknz · May 2, 2017 · Viewed 11.4k times · Source

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?

Answer

Gerald Versluis picture Gerald Versluis · May 2, 2017

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.