Reputation: 61
I am new to Xamarin. I have a question about ListView in Xamarin form. How do I know which row or index everytime I tab (or select) in the listView? Below is the code I tried, but e.SelectedItem does not show anything. Thanks for helping.
listView.ItemSelected += async (sender, e) => {
if (e.SelectedItem == null) return; // don't do anything if we just de-selected the row
await DisplayAlert("Tapped", e.SelectedItem + " row was selected", "OK");
((ListView)sender).SelectedItem = null; // de-select the row
};
Upvotes: 4
Views: 12648
Reputation: 679
A simpler and quicker solution for this would be to use IndexOf on the ItemSource - in your case "people"
int index = people.IndexOf(person);
this would remove your for loop
Upvotes: 0
Reputation: 11787
I have a list view and on click I have to go to the details view page. The following is the code that I use for the same.
listView.ItemSelected += async (sender, e) =>
{
if (e.SelectedItem == null)
{
// don't do anything if we just de-selected the row
return;
}
else
{
Resource resource = e.SelectedItem as Resource;
listView.SelectedItem = null;
await Navigation.PushAsync(new ResourceDetails(resource));
}
};
In your case I would modify the code as follows :
listView.ItemSelected += async (sender, e) => {
if (e.SelectedItem == null) return; // don't do anything if we just de-selected the row
await DisplayAlert("Tapped", (e.SelectedItem as YourDataType).Name + " row was selected", "OK");
((ListView)sender).SelectedItem = null; // de-select the row
};
Upvotes: 6
Reputation: 61
I found the solution how to find the index of the row. :)
listView.ItemSelected += async (sender, e) => {
if (e.SelectedItem == null) return; // don't do anything if we just de-selected the row
Person person = (Person)e.SelectedItem;
int index = -1;
for(int i = 0; i < people.Count; i++)
{
if(people[i] == person)
{
index = i;
break;
}
}
await DisplayAlert("Tapped", person.Name + " row was selected " + index.ToString(), "OK");
((ListView)sender).SelectedItem = null; // de-select the row
};
Upvotes: 0