Monodroid ListView获取所选项目类型转换错误

时间:2012-07-06 11:16:31

标签: android xamarin.android android-4.0-ice-cream-sandwich

我对listview项目有这个问题,并希望你们可以帮我解决这个问题。 我的目标是用列表填充列表视图,当用户触摸这些项目时,我想要加载另一个视图。添加项目工作正常,但是当我从所选项目中获取值并将其强制转换为正确的对象时,它会附带“'无效的强制转换'无法投射......”并崩溃。

仅供参考,我使用Android 4.0 sim,这些是代码的一部分:

SetContentView(Resource.Layout.ArchiveList);
ListView lstArchiveList = FindViewById<ListView>(Resource.Id.lstArchive);

if (lstArchiveList != null) {
    ArrayAdapter<MobileContracts.Archive> archivesAdapter = new 
         ArrayAdapter<MobileContracts.Archive>(this, Resource.Layout.ListItem, sessionData.Archives.Archive);
    lstArchiveList.Adapter = archivesAdapter;
    lstArchiveList.TextFilterEnabled = true;
    lstArchiveList.ItemClick += new EventHandler<AdapterView.ItemClickEventArgs>(lstArchiveList_ItemClick);
    archivesAdapter.NotifyDataSetChanged();
}

OnClick事件处理程序:

void lstArchiveList_ItemClick(object sender, AdapterView.ItemClickEventArgs e) {
    SetContentView(Resource.Layout.SearchDocuments);
    ListView lstEditableIndexList = FindViewById<ListView>(Resource.Id.lstEditableIndexList);
    if (lstEditableIndexList != null) {

        Console.WriteLine("sender type: {0}", sender.GetType().FullName); 

        Object currentItem = e.Parent.GetItemAtPosition(e.Position);
        MobileContracts.Archive selectedArchive = (MobileContracts.Archive) currentItem; //invalid cast?

        Toast.MakeText(Application, selectedArchive.Name + " => " + selectedArchive.Id, ToastLength.Short).Show();
}

任何帮助表示赞赏。非常感谢。

干杯,Inoel

1 个答案:

答案 0 :(得分:1)

没关系,我想出来了。

替换它:

MobileContracts.Archive selectedArchive = (MobileContracts.Archive) currentItem; //invalid cast?

用这个:

System.Reflection.PropertyInfo propertyInfo = currentItem.GetType().GetProperty("Instance");
MobileContracts.Archive selectedArchive = propertyInfo.GetValue(currentItem, null) as MobileContracts.Archive;