以编程方式触发 ListView.SelectedIndexChanged 事件?
如何以编程方式触发 ListView 的 SelectedIndexChanged 事件?
我打算在用户完成特定操作后自动选择 ListView 中的第一项。 SelectedIndexChanged 事件中已存在用于突出显示所选项目的代码。 该项目不仅无法突出显示,而且永远不会命中 SelectedIndexChanged 中设置的断点。 此外,Debug.WriteLine 无法生成输出,因此我相当确定该事件尚未触发。
以下代码无法触发事件:
listView.Items[0].Selected = false;
listView.Items[0].Selected = true;
listView.Select();
Application.DoEvents();
额外的 .Select() 方法调用是为了更好的措施而包含的。 ;) 取消选择 (.Selected = false) 是为了取消选择 .Items 集合中的 ListViewItem,以防默认情况下选择它,因此将其设置为“true”将不起作用。 “Application.DoEvents()”调用是另一个最后的方法。
上面的代码不应该导致 SelectedIndexChanged 事件触发吗?
我应该提到,当通过键盘或鼠标输入选择项目时,SelectedIndexChanged 事件会正确触发。
How can one programmatically fire the SelectedIndexChanged event of a ListView?
I've intended for the first item in my ListView to automatically become selected after the user completes a certain action. Code already exists within the SelectedIndexChanged event to highlight the selected item. Not only does the item fail to become highlighted, but a breakpoint set within SelectedIndexChanged is never hit. Moreover, a Debug.WriteLine fails to produce output, so I am rather certain that event has not fired.
The following code fails to fire the event:
listView.Items[0].Selected = false;
listView.Items[0].Selected = true;
listView.Select();
Application.DoEvents();
The extra .Select() method call was included for good measure. ;) The deselection (.Selected = false) was included to deselect the ListViewItem in the .Items collection just in case it may have been selected by default and therefore setting it to 'true' would have no effect. The 'Application.DoEvents()' call is yet another last ditch method.
Shouldn't the above code cause the SelectedIndexChanged event to fire?
I should mention that the SelectedIndexChanged event fires properly on when an item is selcted via keyboard or mouse input.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
通过将其设置为 false 来取消选择不会触发该事件,但将其设置为 true 则会触发该事件。
你可能还有其他事情发生。 您在什么事件中运行您的选择代码?
Deselecting it by setting it to false won't fire the event but setting it to true will.
You might have something else going on. What event are you running your selection code?
为什么不能将当前位于事件处理程序方法中的代码移动到可以从原始位置以及代码中调用的方法中?
像这样的东西:
将被重构为:
Why can't you move the code that is currently inside your event handler's method into a method that can be called from the original spot and also from your code?
Something like this:
would be refactored to this:
如果您创建从
ListView
派生的类,则可以调用受保护的方法OnSelectedIndexChanged
。 这将触发SelectedIndexChanged
事件。If you create a class derived from
ListView
, you can call the protected methodOnSelectedIndexChanged
. This will fire theSelectedIndexChanged
event.