双击 ListView 中的项目
所以我添加了一个列表视图,每个视图中显示 3 列字符串。我还打开了全行选择。我希望能够双击其中一行,并让它返回第三列中的字符串。我试图到处寻找解决方案,但到目前为止还没有任何结果。
到目前为止,我的代码是:
private void listView_MouseDoubleClick(object sender, MouseEventArgs e)
{
MessageBox.Show(songList.SelectedItems[2].ToString());
}
但它返回一个错误,指出“InvalidArgument=‘2’的值对于‘index’无效。 参数名称:索引”
So I added a list view, and I am displaying 3 columns of strings in each. I also have the full row select on. I want to be able to double click on one of the rows, and have it return the string in the 3rd column. I've tried to look everywhere for a solution to this, but so far nothing comes up.
My code so far is:
private void listView_MouseDoubleClick(object sender, MouseEventArgs e)
{
MessageBox.Show(songList.SelectedItems[2].ToString());
}
Yet it returns an error saying "InvalidArgument=Value of '2' is not valid for 'index'.
Parameter name: index"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以尝试:
采用
ListViewItem
,您可以使用SubItems[]
属性获取列值。You could try:
Taken a
ListViewItem
, you can take columns values usingSubItems[]
property.我认为您不应该将 listView 绑定到 doubleClick 事件,而应该将 listViewItem 绑定到。发送者将有 DataContext,您可以从中获取第三列。
I think that you hould bound not your listView to doubleClick event, but listViewItem. sender will have DataContext, from which you can get your third column.
如何填充
ListView
?如果不知道这一点,就很难提供帮助。也许您可以尝试以下操作:在这一行中设置一个断点:
一旦调试器到达断点,您就可以选择
songList
并按 Shift-F9。现在您可以探索
songList
并自行检查如何获取第三列的字符串。How do you fill the
ListView
? Wihtout knowing this, it's difficult to help. May be you could try this:Set a breakpoint in this line:
As soon as the debugger hits the breakpoint you could select
songList
and hit Shift-F9.Now you can explore the
songList
and check yourself how to get the string of the third column.SelectedItems 返回一个 SelectedListViewItemCollection,并且使用索引器您可以访问此集合中的元素,即 ListViewItems,而不是列。这意味着,如果您选择了一行,则该集合仅包含一项,并且尝试访问第三项会出现错误。
尝试(根据Marco的评论进行编辑):
SelectedItems returns a SelectedListViewItemCollection and with the indexer you are accessing elements in this collection, i.e. ListViewItems, not the columns. this means that if you have a single row selected the collection contains only one item, and trying to access the third one gives you the error.
Try (edit according to Marco's comment):