如何获取选中的ListBox项的索引
抱歉问了一个愚蠢的问题。 我的 WPF UI 的行为让我发疯。 我希望能够选择显示字符串列表的列表框中的单个项目。
<ListBox x:Name="CTnames" Grid.Column="80" Grid.Row="5"
Height="700" d:ItemsSource="{d:SampleData}"
scrollViewer.VerticalScrollBarVisibility="Visible"
scrollViewer.CanContentScroll="True" Margin="20,10,560,100"
Grid.ColumnSpan="16" SelectionMode="Single" Selected="CTnames_Selected" />
如果我列出列表框的属性并单击事件符号(闪电),我可以看到“选定”是一个列表框事件。我双击它,Visual Studio 生成方法“CTnames_SelectionChanged(object sender, SelectionChangedEventArgs e)” 在这样的方法中,我想获取列表框中所选字符串的索引。
public int CTindex { get; set; }
private void CTnames_Selected(object sender, RoutedEventArgs e)
{
CTindex = CTnames.SelectedIndex;
}
不幸的是,编译器在 XAML 文件中与 ListBox 定义对应的行返回以下错误:
“严重性代码说明项目文件行” 错误 CS1061“ListBox”不包含“Selected”的定义,并且找不到接受“ListBox”类型的第一个参数的可访问扩展方法“Selected”(是否缺少 using 指令或程序集引用?)WPFUI C: \Users\mauram\Desktop\WPFDemo_Dapper\WPFUI\MainWindow.xaml 142"
我无法理解这样的错误,因为列出了“选定”通过 Visual Studio 作为 ListBox 事件
我的目标是获取所选项目的索引并使用它来获取将在另一个 ListBox 中显示的另一个字符串列表
。
Sorry to ask a silly question.
The behavior of my WPF UI is driving me crazy.
I would like to be able to select the single items in a ListBox that displays a list of strings.
<ListBox x:Name="CTnames" Grid.Column="80" Grid.Row="5"
Height="700" d:ItemsSource="{d:SampleData}"
scrollViewer.VerticalScrollBarVisibility="Visible"
scrollViewer.CanContentScroll="True" Margin="20,10,560,100"
Grid.ColumnSpan="16" SelectionMode="Single" Selected="CTnames_Selected" />
If I list the properties of the ListBox and click on the Event symbol (lightning bolt) I can see that "Selected" is a ListBox event. I double click on it and Visual Studio generates the method "CTnames_SelectionChanged(object sender, SelectionChangedEventArgs e)"
Inside such a method I would like to get the index of the selected string in the ListBox.
public int CTindex { get; set; }
private void CTnames_Selected(object sender, RoutedEventArgs e)
{
CTindex = CTnames.SelectedIndex;
}
Unluckily, the compiler returns the following error in the XAML file at the line corresponding to the definition of the ListBox:
"Severity Code Description Project File Line
Error CS1061 'ListBox' does not contain a definition for 'Selected' and no accessible extension method 'Selected' accepting a first argument of type 'ListBox' could be found (are you missing a using directive or an assembly reference?) WPFUI C:\Users\mauram\Desktop\WPFDemo_Dapper\WPFUI\MainWindow.xaml 142"
I cannot understand such an error because "Selected" is listed by Visual Studio as a ListBox event.
My goal is to get the index of the selected item and use it to get another list of strings that will be displayed in another ListBox.
Thank you in advance for your help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个示例,给出了列表框中所选项目的索引。
在 Mainwindow.Xaml 文件中
在 MainWindow.cs flie 中 --
Here is a sample that gives index of selected item in ListBox.
In Mainwindow.Xaml file
In MainWindow.cs flie --