[英]Getting the text value selected in at ListBox in C#
我有一个清单框
<Label Content="Report" HorizontalAlignment="Left" Height="47" Margin="36,75,0,0" VerticalAlignment="Top" Width="63"/>
<ListBox x:Name="ListBox1" HorizontalAlignment="Left" Height="121" Margin="84,75,0,0" VerticalAlignment="Top" Width="102" SelectionChanged="ListBox_SelectionChanged" SelectedIndex="-1">
<ListBox Height="100" Width="100" SelectionChanged="ListBox_SelectionChanged_1">
<ListBoxItem x:Name="ListBoxFAT" Content="FAT"/>
<ListBoxItem x:Name="ListBoxNUMI" Content="NUMI"/>
<ListBoxItem x:Name="ListBoxSSID" Content="SSID"/>
<ListBoxItem x:Name="ListBoxFact" Content="FACT"/>
</ListBox>
</ListBox>
这是通过从工具栏拖动列表框图标创建的。 我添加了项目及其值。
现在,我试图获取所选项目的文本值。
private void ListBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
string text = (string)ListBox1.SelectedValue;
MessageBox.Show(text);
我也尝试过SelectedItem
string text = (string)ListBox1.SelectedItem;
但是消息框始终为空。
这应该很简单,但是我已经研究了好几个小时,并且尝试了所有关于stackoverflow的建议或答案。 大多数建议甚至都没有编译。 例如:
string selected = listBox1.GetItemText(listBox1.SelectedValue);
不会编译。 找不到GetItemText。 我正在使用Visual Studio17。“'ListBox不包含'GetItemText'的定义...”
有什么想法吗? 请指教。 谢谢。
感谢您的评论,查尔斯。 我做到了 再玩一点,现在我得到了
System.InvalidCastException: 'Unable to cast object of type 'System.Windows.Controls.ListBoxItem' to type 'System.String'.' string text = (string)ListBox1.SelectedItem;
在标记中, SelectedIndex
设置为-1,表示没有选择。 在这种情况下, SelectedValue
和SelectedItem
都返回null。 您可以通过将SelectedIndex
设置为0到3之间的值来解决此问题,也可以通过准备代码来处理SelectedValue
和SelectedItem
的空值来解决此问题,例如
string text = (ListBox1.SelectedItem as ListBoxItem)?.Content?.ToString();
这不会引发错误,因此用户可以随后选择一个项目。 选择后,文本应按预期显示。
正如Charles May所指出的,您的XAML显示您的ListBox在另一个ListBox中,这就是为什么您会引发错误的原因。
名为“ ListBox_SelectionChanged_1”的事件绑定到未命名的ListBox1内部的ListBox对象。
我相信您正在寻找的行为将是固定的,如下所示:
XAML:
<Label Content="Report" HorizontalAlignment="Left" Height="47" Margin="36,75,0,0" VerticalAlignment="Top" Width="63"/>
<ListBox x:Name="ListBox1" HorizontalAlignment="Left" Height="121" Margin="84,75,0,0" VerticalAlignment="Top" Width="102" SelectionChanged="ListBox_SelectionChanged" SelectedIndex="-1">
<ListBoxItem x:Name="ListBoxFAT" Content="FAT"/>
<ListBoxItem x:Name="ListBoxNUMI" Content="NUMI"/>
<ListBoxItem x:Name="ListBoxSSID" Content="SSID"/>
<ListBoxItem x:Name="ListBoxFact" Content="FACT"/>
</ListBox>
背后的代码:
private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string text = ((sender as ListBox)?.SelectedItem as ListBoxItem)?.Content.ToString();
MessageBox.Show(text);
}
或至少接近此解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.