3

Goal

If there is 1 or more items in the listview and the user clicks in the whitespace of the ListView, the item selected should stay selected.

In other words, if an item is selected it should stay selected unless another item is chosen.

Current Situation

I have the property of the ListView HideSelection set to false which will make the selected ListViewItem stay selected when the control loses focus. However, this does not solve the issue when I click in the whitespace of the Listview.

Any suggestions?

Alex
  • 4,821
  • 16
  • 65
  • 106
  • That will be problematic. If you force a selection in the SelectedIndex changed event, you can end up with 2 items selected in SingleSelect mode because the event fires twice. 1st - the old item is DESELECTED, your code sees nothing selected, so you manually select one, e.g. Item(0); 2nd - the item clicked fires the event to SELECT it leaving you with 2 items selected which is confusing to the user. Also, HideSelection doesnt do anything to deselect items, it just paints a selection cue for a selected item when the LV does not have focus. Try to eat the click event when it is not on an item – Ňɏssa Pøngjǣrdenlarp Feb 06 '14 at 14:43

1 Answers1

4

You can achieve this by subclassing the ListView:

Public Class UIListView
    Inherits ListView

    Private Sub WmLButtonDown(ByRef m As Message)
        Dim pt As Point = New Point(m.LParam.ToInt32())
        Dim ht As ListViewHitTestInfo = Me.HitTest(pt)
        If (ht.Item Is Nothing) Then
            m.Result = IntPtr.Zero
        Else
            MyBase.WndProc(m)
        End If
    End Sub

    Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
        Select Case m.Msg
            Case WM_LBUTTONDOWN
                Me.WmLButtonDown(m)
                Exit Select
            Case Else
                MyBase.WndProc(m)
                Exit Select
        End Select
    End Sub

    Private Const WM_LBUTTONDOWN As Integer = &H201

End Class
Bjørn-Roger Kringsjå
  • 9,849
  • 6
  • 36
  • 64