2013-06-25 109 views
1

在我的課中,我爲ListBoxItem寫了雙擊事件。當單擊列表框的條目時,它應該只返回該特定條目。但在我的情況下,雖然我點擊了單個條目,但所有條目都返回併發生「InvalidCastException」。所以,我應該如何改變才能獲得單一入場。發生類型'System.InvalidCastException'的第一次機會異常

這裏是雙擊事件代碼:

private void ListBoxItem_DoubleClick(object sender, RoutedEventArgs e) 
    { 
     //Submit clicked Entry 
     Harvest_TimeSheetEntry entryToPost = (Harvest_TimeSheetEntry)sender; 

      if (!entryToPost.isSynced) 
      { 
       //Check if something is selected in selectedProjectItem For that item 
      if (entryToPost.ProjectNameBinding == "Select Project") 
        MessageBox.Show("Please Select a Project for the Entry"); 
       else 
        Globals._globalController.harvestManager.postHarvestEntry(entryToPost); 
      } 
      else 
      { 
       //Already synced.. Make a noise or something 
       MessageBox.Show("Already Synced;TODO Play a Sound Instead"); 
      } 
    } 

In xml: 

<ListBox x:Name="listBox1" ItemsSource="{Binding}" Margin="0,131,0,59" ItemTemplateSelector="{StaticResource templateSelector}" ListBoxItem.MouseDoubleClick="ListBoxItem_DoubleClick"/> 
+0

什麼行會拋出無效的轉換異常?你確定發件人是Harvest_TimeSheetEntry嗎?根據你的解釋,我不認爲它是。 –

+2

您可以使用ListBox.SelectedItem獲取雙擊事件中的點擊項目 –

+0

此行顯示異常 - Harvest_TimeSheetEntry entryToPost =(Harvest_TimeSheetEntry)sender; – Dinesh

回答

4

ListBox中隱含的包裝物品進入ListBoxItem。試着投senderListBoxItem然後利用其Content財產

+0

我試着用這種方式鑄造 - ListBoxItem item =(ListBoxItem)sender; – Dinesh

+0

但我希望Harvest_TimeSheetEntry中的項目,因爲進一步的功能取決於它。 – Dinesh

+0

ListBoxItem的Call Content屬性。添加了這個來回答 – Demarsch

0

嘗試以操作員身份,而不是直接鑄造使用,包括空檢查進一步處理

0

最後,它的工作原理之前。

private void listBox1_MouseDoubleClick(object sender, MouseButtonEventArgs e) 
    { 
     //Submit clicked Entry 
     try 
     { 
      ListBoxItem item = (ListBoxItem)sender; 
      Harvest_TimeSheetEntry entryToPost = (Harvest_TimeSheetEntry)item.Content; 

      if (!entryToPost.isSynced) 
      { 
       //Check if something is selected in selectedProjectItem For that item 
       if (entryToPost.ProjectNameBinding == "Select Project") 
        MessageBox.Show("Please Select a Project for the Entry"); 
       else 
        Globals._globalController.harvestManager.postHarvestEntry(entryToPost); 
      } 
      else 
      { 
       //Already synced.. Make a noise or something 
       MessageBox.Show("Already Synced;TODO Play a Sound Instead"); 
      } 
     } 
     catch (Exception) 
     { } 
    } 
相關問題