2013-06-25 3 views
1

클래스에서 ListBoxItem에 대한 DoubleClick 이벤트를 작성했습니다. listBox 항목을 클릭하면 해당 항목 만 반환됩니다. 하지만 제 경우에는 단일 항목을 클릭했지만 모든 항목이 반환되고 "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) 보낸 사람을 표시합니다. – Dinesh

답변

4

옵니다 암시 ListBoxItem에 해당 항목을 래핑 :

여기에 더블 클릭 이벤트 코드입니다. 운영자 대신 직접 주조로 사용하기 위해 Content 특성 다음 걸릴 ListBoxItemsender 캐스팅

+0

이 방법으로 캐스팅을 시도했습니다. ListBoxItem item = (ListBoxItem) sender; – Dinesh

+0

하지만 Harvest_TimeSheetEntry에서이 항목을 사용하려면 추가 기능이 필요합니다. – Dinesh

+0

ListBoxItem의 Content 속성을 호출합니다. – Demarsch

0

마지막으로, 그것은 작동하기 전에 NULL 체크를 포함한다.

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) 
     { } 
    }