2012-07-06 22 views
1

我有這個問題與listview項目,並希望你們可以幫我解決這個問題。 我的目標是填充列表視圖,當用戶觸摸這些項目時,我想要加載另一個視圖。添加項目工作正常,但是當我從選定的項目中獲取值並將它轉換爲正確的對象時,它會出現「無效投射」無法投射......「並崩潰。Monodroid ListView得到選定的項目typecast錯誤

僅供參考,我用的是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(); 
} 

任何幫助表示讚賞。提前感謝很多。

Cheers,Inoel

回答

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;