简体   繁体   English

如何从 xamarin forms 中的列表视图中获取所选项目索引?

[英]How to get the selected item index from the listview in xamarin forms?

Here i want to display the selected item index in Xamarin Forms listview in below code iam getting InvalidCastException in e.SelectedItemIndex.在这里,我想在下面的代码中显示 Xamarin Forms 列表视图中的选定项目索引 iam 在 e.SelectedItemIndex 中获取 InvalidCastException。

 private async void animelist_ItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            var si = (Applications)animelist.SelectedItem;
            string i = Convert.ToString(e.SelectedItemIndex);
            await DisplayAlert("Info",i,"Ok");
        }

Here's is a code snippet that works for me and I believe should work for you.这是一个适合我的代码片段,我相信它应该适合你。

 //change Core.Models.Data.TaskItem to the object you want to cast to.
 var SelectedItem = (Core.Models.Data.TaskItem)e.SelectedItem;

 await DisplayAlert("Info", $"{SelectedItem.Description}}", "Ok");
 //where SelectedItem.Description is a field in my model

The reason you got an invalid cast exception is that animelist.SelectedItem is of type ListView.SelectedItem and you're trying to cast it Application type.您收到无效演员表异常的原因是animelist.SelectedItem的类型为ListView.SelectedItem 并且您正在尝试将其转换为Application类型。 Using e.SelectedItem as shown in the sample will take on the generic type of your listView binding model.如示例中所示,使用 e.SelectedItem 将采用您的 listView 绑定 model 的泛型类型。

Let me know if this helps.让我知道这是否有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM