jwknz
jwknz

Reputation: 6824

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?

Upvotes: 4

Views: 16243

Answers (3)

Magnus7
Magnus7

Reputation: 69

You listview is lstInfo uses ItemSelected for select the listview

lstInfo.ItemSelected += (sender, e) =>
                {
                    //get all data in you row in the listview "lstinfo"
                    //And MFoto is you Model {get; set}
                    var item = e.SelectedItem as MFoto;

                    //View id for you listview
                    DisplayAlert("Data", item.Id, "OK");

                };

Upvotes: -1

Gerald Versluis
Gerald Versluis

Reputation: 34128

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.

Upvotes: 13

Alessandro Caliaro
Alessandro Caliaro

Reputation: 5768

I think you can search the SelectedItem in your List.

For Example, in your ViewModel you have an ObservableCollection (MyList for example).

You have binded (in Xaml) this Collection to your PeopleList

then you can do something like

int myindex = MyList.IndexOf(SelectedItem);

for example

    ObservableCollection<string> l = new ObservableCollection<string>();
    l.Add("AAA");
    l.Add("BBB");
    l.Add("CCC");
    int idx = l.IndexOf("BBB");
    System.Diagnostics.Debug.WriteLine("idx = " + idx.ToString());

Upvotes: 0

Related Questions