【问题标题】:Stop items in a list view from being selected on right click阻止列表视图中的项目在右键单击时被选中
【发布时间】:2014-03-21 12:40:37
【问题描述】:

我在 VB 2010 的 Windows 窗体上有一个 ListView。

我已将ListViewMultiSelect 属性设置为False,这样任何时候都只能选择一项。

我为ListView 配置了一个上下文菜单,当ListView 被右键单击时它会正确显示。

[在设计器中添加了ContextMenuStrip 控件并将ListViewContextMenuStrip 属性设置为此。]

考虑以下两种情况:

  1. 用户右键单击已在 ListView 中选择的项目。然后显示上下文菜单,没有问题。

  2. 用户右键点击ListView中的已选中项目以外的项目,然后在显示上下文菜单之前,用户右键单击的项目是已选中。

在场景 2 中,我需要阻止用户右键单击的项目被自动选中。需要显示上下文菜单,但之前选择的项目应保持选中状态。

我怎样才能做到这一点?

我注意到在ListViewMouseDown 事件中,SelectedItems.Item(0).Index 属性仍处于旧索引中。但是,在 MouseUp 事件中,此属性会更改为新索引。

MouseDown 事件处理程序或其他任何地方,如何阻止SelectedItems 更改?或者我怎样才能将它改回之前选择的项目(没有用户注意到它正在被更改,然后又改回来)?

我可以使用下面的代码右键单击MouseDownMouseUp。但是,我不确定我需要在此条件中添加什么来阻止 SelectedItems 更改。

    If e.Button = Windows.Forms.MouseButtons.Right Then
        ...
    End If

注意:我可以为此使用以下代码。但是,当我在场景 (2) 中使用它时,它会选择用户右键单击的项目,然后将其更改回上一个项目,用户可以看到此更改。因此无法使用此解决方案。

Dim intPrevSelectedIndex As Integer = -1
Dim boolCancel As Boolean = False
Private Sub ListView1_MouseDown(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles ListView1.MouseDown
    If ListView1.SelectedItems.Count > 0 AndAlso e.Button = Windows.Forms.MouseButtons.Right Then
            boolCancel = True
            intPrevSelectedIndex = ListView1.SelectedItems(0).Index
        End If
End Sub

Private Sub ListView1_MouseUp(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles ListView1.MouseUp
    If boolCancel Then
        lstWalkResults.Items(intPrevSelectedIndex).Selected = True
        boolCancel = False
    End If
End Sub

请告诉我您可能有的任何解决方案。感谢您的宝贵时间!

【问题讨论】:

    标签: vb.net listview contextmenu right-click contextmenustrip


    【解决方案1】:

    在后面的代码中你应该能够处理右键单击事件。在该方法中,您将手动显示上下文菜单,然后忽略阻止选择项目的单击事件。

    If e.Button = Windows.Forms.MouseButtons.Right Then
        //display context menu because you're handling the click event manually.
        ...context menu code...
        Dim ee As New System.Windows.Forms.MouseEventArgs(Forms.MouseButtons.None, e.Clicks, e.X, e.Y, e.Delta)
        e = ee
    End If
    

    【讨论】:

    • e.Handled = true 不起作用。我收到错误:'Handled' is not a member of 'System.Windows.Forms.MouseEventArgs'.
    • 对 MouseEventArgs 的快速谷歌搜索找到了解决方案。请参阅我修改后的答案。
    • 我试过了。 Dim Hme As HandledMouseEventArgs = e 导致错误:Unable to cast object of type 'System.Windows.Forms.MouseEventArgs' to type 'System.Windows.Forms.HandledMouseEventArgs'.
    • 用您根据我的建议尝试过的内容以及错误所在更新您的问题。我提供的答案应该有效,请参阅此 MSDN 帖子,其中显示了我在回答中向您展示的内容:msdn.microsoft.com/en-us/library/…
    • 提供的MSDN link中提到的HandledMouseEventArgs是为了防止MouseWheel事件被发送到其父容器。它不适用于MouseDown 事件。
    猜你喜欢
    • 2012-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-01
    相关资源
    最近更新 更多