在列表视图中未选择任何项目时必须丢失焦点

时间:2013-02-11 08:32:15

标签: .net vb.net listview lost-focus

我相信这很容易,但我现在正遇到这个问题。 我有一个列表视图,每次单击一个项目时,我都将其名称存储在字符串变量中。会发生的是,当我单击列表视图上的某个项目然后再次单击列表视图而不选择任何项目时,它不会丢失焦点并将先前所选项目的名称存储在字符串变量中。我想要发生的是每次单击一个项目然后在列表视图内部或外部单击而不选择任何项目时,它必须失去焦点而不是将项目的名称存储在字符串变量上。

Private Sub lvReceivedFiles_MouseClick(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles lvReceivedFiles.MouseClick

    If e.Button = Windows.Forms.MouseButtons.Left Then

        If lvRecievedFiles.FocusedItem.Selected = True

              lvReceivedFiles.FullRowSelect = True

              'When an item is clicked in the list view, store its name.
              fName = "\" & Path.GetFileName(lvReceivedFiles.FocusedItem.Text)

        Else

              'This part here doesn't make any sense because it doesn't execute
              'every time I click in the list view without selecting any item.
              'ListView.FocusedItem.Selected is always true.

        End If

    End If

End Sub

2 个答案:

答案 0 :(得分:0)

处理这种情况的更好方法是使用SelectedIndexChanged事件而不是使用MouseClick事件。检查此代码。

Private Sub ListView1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles lvReceivedFiles.SelectedIndexChanged

If lvRecievedFiles.FocusedItem.Selected = True

          lvReceivedFiles.FullRowSelect = True

          'When an item is clicked in the list view, store its name.
          fName = "\" & Path.GetFileName(lvReceivedFiles.FocusedItem.Text)

Else

          'This part here doesn't make any sense because it doesn't execute
          'every time I click in the list view without selecting any item.
          'ListView.FocusedItem.Selected is always true.

End If

End Sub

答案 1 :(得分:0)

您可以尝试MouseUp event

Private Sub lvlcheckin_MouseUp(sender As Object, e As MouseEventArgs) Handles lvlcheckin.MouseUp
    If e.Button = Windows.Forms.MouseButtons.Left Then

        If lvlcheckin.FocusedItem.Selected = True Then
            lvlcheckin.FullRowSelect = True
        Else
            lvlcheckin.FullRowSelect = False
        End If
    End If
End Sub