How to keep an item selected? - ListView

烈酒焚心 提交于 2019-12-10 00:26:44

问题


I would like to keep an item selected, on a ListView, when the user clicks on a space which has no item. For example, the space below the items, but still on the ListView component. I've change the ListView property "HideSelection" to false, but that only works when the focus is changed to another component; not when the user clicks on the ListView itself. Thanks!


回答1:


This is something you normally shouldn't fix. The user clicked somewhere intentionally, that might well be because she wanted to deselect an item. If it was unintentional then she'll understand what happened and know how to correct it. Giving standard controls non-standard behavior tends to only confuse the user.

But you can fix it. You'll need to prevent the native ListView control from seeing the click. That requires overriding the WndProc() method and checking where the click occurred. Add a new class to your project and paste the code shown below. Compile. Drop the new control from the top of the toolbox onto the form.

using System;
using System.Drawing;
using System.Windows.Forms;

class MyListView : ListView {
  protected override void WndProc(ref Message m) {
    if (m.Msg == 0x201 || m.Msg == 0x203) {  // Trap WM_LBUTTONDOWN + double click
      var pos = new Point(m.LParam.ToInt32());
      var loc = this.HitTest(pos);
      switch (loc.Location) {
        case ListViewHitTestLocations.None:
        case ListViewHitTestLocations.AboveClientArea:
        case ListViewHitTestLocations.BelowClientArea:
        case ListViewHitTestLocations.LeftOfClientArea:
        case ListViewHitTestLocations.RightOfClientArea:
          return;  // Don't let the native control see it
      }
    }
    base.WndProc(ref m);
  }
}



回答2:


One way: on the SelectedIndexChanged event, check to see if the value is -1; if so, reset it to the previous value (which you maybe stored in a variable...)



来源:https://stackoverflow.com/questions/2529743/how-to-keep-an-item-selected-listview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!