访问列表框,当我有下面的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