我有一个列表框,其中包含以下从XMLReader填充的xaml
<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>我想在选择列表框时呼叫电话,所以我创建了以下类
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。
是什么导致了这个错误?
发布于 2012-05-09 03:49:50
从发布的XAML来看,没有绑定到ListBox的集合。这要么意味着没有绑定,要么是在后面的代码中设置了绑定。因为没有发布额外的代码,所以下面的代码只是在黑暗中拍摄的:
正确绑定ListBox
假设集合是DataContext的一部分,则需要将该集合绑定到ListBox
<ListBox ItemsSource="{Binding Path=MyCollection}"... />启动资源:MSDN: How to: Bind to a Collection and Display Information Based on Selection
在强制转换之前,验证对象
这可能是所选项目为空的情况,即列表中的第一个项目没有值。在这种情况下,请先检查对象是否为您期望的类型,然后再执行其他操作:
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();
}Other Thoughts
我怀疑可能没有绑定到ListBox`的集合;也许应该有一些代码隐藏来设置未执行的绑定?
最后,如果以上情况都不适用于您的情况,请使用创建集合的相关代码编辑帖子,并将集合设置为ListBox的ItemsSource。
https://stackoverflow.com/questions/9776165
复制相似问题