[英]How to keep other items selected in System.Windows.Forms.ListView when deselecting one item
When you have multiple items selected in a ListView
and you click one of the selected items, the default behavior is for all the other items to become deselected, leaving just the that was clicked selected.当您在ListView
选择了多个项目并单击其中一个选定项目时,默认行为是取消选择所有其他项目,只保留被单击的项目。 I'd like the exact inverse behavior: clicking one of the selected items deselects just that item and leaves the other items selected.我想要完全相反的行为:单击选定的项目之一会取消选择该项目并保持其他项目处于选中状态。
I've seen answers like this one and this one .我见过类似的回答这一个和这一个。 The first is talking about preventing the mouse click from doing anything which isn't what I want obviously, and the second is about cancelling the index changing event.第一个是谈论防止鼠标点击做任何我不想要的事情,第二个是关于取消索引更改事件。 I tried adapting the latter for my needs, but it still results in the other items becoming deselected.我尝试根据我的需要调整后者,但它仍然导致其他项目被取消选择。
private void HandleIncludableFilesListViewSelectedIndexChanging
(object sender, Controls.Events.ListViewItemChangingEventArgs e)
{
if (_includableFilesListView.Items[e.Index].Selected) e.Cancel = true;
}
The above event handler only fires for the single item that is clicked on, and not for every other item as they're being deselected.上面的事件处理程序只为被点击的单个项目触发,而不是为每个其他项目被取消选择触发。
Is there some way to achieve this?有什么方法可以实现这一目标吗?
As an option you can override DefWndProc
and handle WM_LBUTTONDOWN
.作为一个选项,您可以覆盖DefWndProc
并处理WM_LBUTTONDOWN
。 Then do hit-test and check if the clicked point is an item, revert the Selected
property of the item:然后进行命中测试并检查单击的点是否为项目,恢复项目的Selected
属性:
public class MyListView : ListView
{
const int WM_LBUTTONDOWN = 0x0201;
protected override void DefWndProc(ref Message m)
{
if (m.Msg == WM_LBUTTONDOWN)
{
int x = (m.LParam.ToInt32() & 0xffff);
int y = (m.LParam.ToInt32() >> 16) & 0xffff;
var item = this.HitTest(x, y).Item;
if (item != null)
item.Selected = !item.Selected;
else
base.DefWndProc(ref m);
}
else
{
base.DefWndProc(ref m);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.