我在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>
问题是字符串文本= myselectedItem.ToString(); 返回null。如何解决这个问题?
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
属性的对象以外的任何东西,这将在运行时失败。如果知道类型,则更可取。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句