I would like to keep an item sele开发者_如何学JAVActed, 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!
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);
}
}
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...)
精彩评论