我正在使用WPF中的数据绑定填充列表,并且一切正常。但是我无法在ListBox中获得所选项目的字符串。
这是我试图获取所选Item的值的按钮代码。
private void hexButton_Click(object sender, RoutedEventArgs e)
{
if (imeiListBox.SelectedIndex == -1)
{
MessageBox.Show("Select IMEi from IMEI List!");
}
else
{
ListBoxItem myselectedItem= imeiListBox.SelectedItem as ListBoxItem;
string text = myselectedItem.ToString();
}
}
这是我的ListBox的XAML代码。
<ListBox x:Name="imeiListBox"
ItemsSource="{Binding Path=Devices}"
HorizontalAlignment="Left"
SelectionChanged="imeiListBox_SelectionChanged" >
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Imei}"/>
</DataTemplate>
</ListBox.ItemTemplate>
问题是 string text = myselectedItem.ToString(); 返回 null 。如何解决这个问题?
答案 0 :(得分:3)
imeiListBox.SelectedItem
将是与您在ItemsSource
的{{1}}中放置的项目具有相同类型的对象,可能是一个ListBox
对象,用于查看代码。
您必须像这样投射
Device
相反。
答案 1 :(得分:2)
SelectedItem
不返回ListBoxItem
。它返回类型(Device
?)的实例,其中定义了Imei
属性。
所以您应该强制转换为这种类型:
var myselectedItem= imeiListBox.SelectedItem as Device;
if (myselectedItem != null)
string text = myselectedItem.Imei.ToString();
或者您可以使用dynamic
关键字:
dynamic myselectedItem= imeiListBox.SelectedItem;
string text = myselectedItem.Imei?.ToString();
请注意,如果SelectedItem
返回具有Imei
属性的对象以外的任何内容,则此操作将在运行时失败。如果知道类型,则最好使用强制转换。