1

我有 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

4

1 回答 1

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;
于 2012-07-06T12:49:13.987 回答