I basically have a listview, with this function when i click on a listview-item.
When i run this and click on the item, i get the following display alerts before my app crashes.
DisplayAlert 1, then DisplayAlert 2, then DisplayAlert 1 and right after this one my app crashes. With "Specified cast is not valid".
I dont know why i get the DisplayAlert 1 again, and why this crashes.
public async void OnSelection(object sender, SelectedItemChangedEventArgs e)
{
await DisplayAlert("1", "1", "1");
if (e.SelectedItem == null)
{
return; // ItemSelected is called on deselection, which results in SelectedItem being set to null
}
//((ListView)sender).SelectedItem = null;
await DisplayAlert("2", "2", "2");
// Cast to zoneviewmodel type
var selectedZone = (ViewModel.ZoneViewModel)e.SelectedItem;
await DisplayAlert("3", "3", "3");
// Redirect to login
await Navigation.PushAsync(new LoginPage(selectedZone.Address));
await DisplayAlert("4", "4", "4");
// send message containing information to fill loginpage information
MessagingCenter.Send<MainPage, ViewModel.ZoneViewModel>(this, "loginInfo", selectedZone);
}
In this line: var selectedZone = (ViewModel.ZoneViewModel)e.SelectedItem;
you're trying to cast whatever is in your list to ViewModel.ZoneViewModel
. The error is telling you this list item is not assignable to this type. If you're not sure what type the item is, step through or print out e.SelectedItem.GetType()
.