訪問列表框,當我有下面的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
。
什麼是造成此錯誤?
設置一個斷點並檢查'listBox4.SelectedItem'來查看它確實是什麼類型。 – 2012-03-19 19:01:22
此外,顯示您將列表中的值分配給ListBox(綁定或代碼隱藏)的位置。 – Robaticus 2012-03-19 19:09:41
我想用下面的代碼替換第一行可能會解決問題 PhoneList nPhone =(PhoneLsit)(sender as listbox).SelectedItem; – TutuGeorge 2012-03-20 08:03:10