如何在取消选择一项时保持 System.Windows.Forms.ListView 中的其他项目处于选中状态

How to keep other items selected in System.Windows.Forms.ListView when deselecting one item

当您在 ListView 中选择了多个项目并单击其中一个项目时,默认行为是取消选择所有其他项目,只保留被单击的项目。我想要完全相反的行为:单击一个选定的项目将仅取消选择该项目并使其他项目保持选中状态。

我看过像 this one and this one 这样的答案。第一个是关于防止鼠标点击做任何我不想做的事情,第二个是关于取消索引更改事件。我尝试根据我的需要调整后者,但它仍然导致其他项目被取消选择。

private void HandleIncludableFilesListViewSelectedIndexChanging
    (object sender, Controls.Events.ListViewItemChangingEventArgs e)
{
   if (_includableFilesListView.Items[e.Index].Selected) e.Cancel = true;
}

上面的事件处理程序只针对被单击的单个项目触发,而不针对所有其他项目,因为它们被取消选择。

有什么方法可以实现吗?

作为一个选项,您可以覆盖 DefWndProc 并处理 WM_LBUTTONDOWN。然后做hit-test检查点击的点是不是item,还原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);
        }
    }
}