Alex
Alex

Reputation: 4948

Prevent ListView From Deselect

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?

Upvotes: 3

Views: 1679

Answers (1)

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

Upvotes: 4

Related Questions