2012-03-19 94 views
0

訪問列表框,當我有下面的XAML代碼從一個XMLReader的填充一個列表框InvalidCastException的代碼隱藏從

<ListBox Name="listBox4" Height="498" SelectionChanged="listBox4_SelectionChanged"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <StackPanel> 
       <TextBlock Text="{Binding Epon}" FontSize="32"/> 
       <TextBlock Text="{Binding Telnum}" FontSize="24" /> 
       <TextBlock Text="{Binding Beruf}" FontSize="16" /> 
       <TextBlock Text="{Binding Odos}" FontSize="16"/> 
       <TextBlock Text="{Binding Location}" FontSize="16"/> 
      </StackPanel> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

我要撥打的電話時,我會選擇lisbox項目,所以我創建了下面的類

public class PhoneList 
{ 
    public string Epon { get; set; } 
    public string Telnum { get; set; } 
    public string Beruf { get; set; } 
    public string Odos { get; set; } 
    public string Location { get; set; } 

    public PhoneList(string Telnum, string Epon, string Beruf, string Odos, string Location) 
    { 
     this.Telnum = Telnum; 
     this.Epon = Epon; 
     this.Beruf = Beruf; 
     this.Odos = Odos; 
     this.Location = Location; 
    } 
} 

在這低於

private void listBox4_SelectionChanged(object sender, SelectionChangedEventArgs e) 
{ 
    PhoneList nPhone = (PhoneList)listBox4.SelectedItem; 
    string mPhoneCopy = nPhone.Telnum; 
    string mNameCopy = nPhone.Epon; 

    var pt = new PhoneCallTask(); 
    pt.DisplayName = mNameCopy; 
    pt.PhoneNumber = mPhoneCopy; 
    pt.Show(); 
} 

我得到的選擇的情況下,在事件的第一行錯誤InvalidCastException

什麼是造成此錯誤?

+0

設置一個斷點並檢查'listBox4.SelectedItem'來查看它確實是什麼類型。 – 2012-03-19 19:01:22

+1

此外,顯示您將列表中的值分配給ListBox(綁定或代碼隱藏)的位置。 – Robaticus 2012-03-19 19:09:41

+0

我想用下面的代碼替換第一行可能會解決問題 PhoneList nPhone =(PhoneLsit)(sender as listbox).SelectedItem; – TutuGeorge 2012-03-20 08:03:10

回答

0

從發佈的XAML中,沒有綁定到ListBox的集合。這或者意味着沒有綁定,或者在後面的代碼中設置綁定。因爲沒有額外的代碼已經被公佈在以下只是在黑暗中拍攝:

正確綁定列表框

假設集合是DataContext的一部分,收集需要綁定到ListBox

<ListBox ItemsSource="{Binding Path=MyCollection}"... /> 

起始資源:MSDN: How to: Bind to a Collection and Display Information Based on Selection

驗證對象Befo鑄造

這可能是所選項目爲空的情況,即列表中的第一個項目沒有值。在這種情況下,請檢查的對象是你在做任何事情之前都期待類型:

private void listBox4_SelectionChanged(object sender, SelectionChangedEventArgs e) 
{ 
    var nPhone = listBox4.SelectedItem as PhoneList; 
    if (nPhone == null) 
    { 
    return; 
    } 

    string mPhoneCopy = nPhone.Telnum; 
    string mNameCopy = nPhone.Epon; 

    var pt = new PhoneCallTask(); 
    pt.DisplayName = mNameCopy; 
    pt.PhoneNumber = mPhoneCopy; 
    pt.Show(); 
} 

其他的想法

我懷疑可能沒有綁定到ListBox`集合;也許應該有一些代碼隱藏來設置未被執行的綁定?最後,如果以上都不適用於您的情況,請編輯與創建集合的相關代碼並將集合設置爲ListBox的ItemsSource的帖子。回到頂端這篇文章中的信息適用於: