Listview多项选择

时间:2020-03-05 18:59:01  来源:igfitidea点击:

有什么方法可以强制Listview控件将所有单击视为通过Control键完成?

我需要复制使用控制键的功能(选择一个项目会设置并取消其选择状态),以便允许用户轻松地同时选择多个项目。

先感谢我们。

解决方案

回答

Ctrl + Click行为是由浏览器实现的,与实际的.NET Control无关。我们尝试获得的结果可以通过使用许多其他JavaScript来获取,最简单的方法可能是从默认情况下构建以这种方式工作的JavaScript控件,而不是试图破坏listview。这是可取的吗?在这种情况下,我可以调查一下并与我们联系以寻求解决方案。

回答

即使MultiSelect设置为true,这也不是ListView控件的标准行为。

如果要创建自己的自定义控件,则需要执行以下操作:

  • 从ListView派生控件
  • 将处理程序添加到" Selected"事件中。
  • 在" OnSelected"中,维护我们自己的所选项目列表。
  • 如果新选择的项目不在列表中,请添加它。如果是的话,将其删除。
  • 在代码中,选择列表中的所有项目。

应该足够简单地实现,并且无需使用控制键就可以像多选一样!

回答

深入研究ListviewItemCollection,可以将单个项目的Selected属性设置为true。我相信,这将模仿我们要重现的"多选"功能。 (此外,正如上面的评论者所述,请确保将lisetview的MultiSelect属性设置为true。)

回答

我们可能还需要考虑在列表视图上使用复选框。这是将多选概念传达给可能不了解Ctrl + Click的普通用户的一种明显方法。

从MSDN页面:

The CheckBoxes property offers a way to select multiple items in the ListView control without using the CTRL key. Depending on your application, using check boxes to select items rather than the standard multiple selection method may be easier for the user. Even if the MultiSelect property of the ListView control is set to false, you can still display checkboxes and provide multiple selection capabilities to the user. This feature can be useful if you do not want multiple items to be selected yet still want to allow the user to choose multiple items from the list to perform an operation within your application.

回答

这是我用来使用WndProc解决此问题的完整解决方案。基本上,它会在单击鼠标时进行命中测试。然后,如果MutliSelect处于打开状态,它将自动打开/关闭[.Selected]项目,而不必担心维护任何其他列表或者使ListView功能混乱。

我尚未在所有情况下都对此进行过测试,但它对我有用。 YMMV。

public class MultiSelectNoCTRLKeyListView : ListView {
  public MultiSelectNoCTRLKeyListView() {

  }

  public const int WM_LBUTTONDOWN = 0x0201;
  protected override void WndProc(ref Message m) {
    switch (m.Msg) {
      case WM_LBUTTONDOWN:
        if (!this.MultiSelect)
          break;

        int x = (m.LParam.ToInt32() & 0xffff);
        int y = (m.LParam.ToInt32() >> 16) & 0xffff;

        var hitTest = this.HitTest(x, y);
        if (hitTest != null && hitTest.Item != null)
          hitTest.Item.Selected = !hitTest.Item.Selected;

        return;
    }

    base.WndProc(ref m);
  }
}