简体   繁体   English

右键单击ContextMenuStrip,在Listview中选择IF项目?

[英]ContextMenuStrip On RightClick, IF Items Are Selected In Listview?

I have a ContextMenuStrip attached to a list view, and it's working great, but what I'm interested in knowing is how I can have it show up only when one or more items are selected in the listview. 我有一个附加到列表视图的ContextMenuStrip,它工作得很好,但我感兴趣的是我只有在列表视图中选择了一个或多个项目时才能显示它。

Thanks! 谢谢!

You could use the Opening event. 您可以使用Opening事件。 The event args has a Cancel property so that you can examine the state of your application and decide whether to have the menu show (by doing nothing) or prevent it from showing (by setting e.Cancel = true ). 事件args具有Cancel属性,因此您可以检查应用程序的状态并决定是否显示菜单(通过执行任何操作)或阻止它显示(通过设置e.Cancel = true )。 However, like @Grzenio mentions, I would find it more intuitive if the item that i right-clicked on became selected automatically. 但是,就像@Grzenio提到的那样,如果我右键单击的项目被自动选中,我会发现它更直观。

Another option would be to use the Opening event to populate the context menu with only one disabled item, with a text like (no item is selected) or so; 另一种选择是使用Opening事件来填充上下文菜单,其中只有一个禁用项目,文本类似(no item is selected) ; this would inform the user about why the command is not available. 这将告知用户该命令不可用的原因。

For other people reading this thread, a nice way is to gray out the options in the menu (in Opening event) when no items are selected instead of not displaying the menu at all 对于阅读此主题的其他人来说,一个不错的方法是在没有选择任何项目而不是根本不显示菜单时使菜单中的选项变灰(在Opening事件中)

if (List.SelectedItems.Count == 0)
{
    // e.Cancel=true;
    List.Enabled = false;
}
else
{
    List.Enabled = true;
}

For me its intuitive that if you have no items selected (or you right-click on a non-selected item), the item would get automatically selected just before you show the context menu. 对我来说直观的是,如果您没有选择任何项目(或右键单击未选择的项目),则会在显示上下文菜单之前自动选择该项目。

If the first solution is not acceptable, I think I would try to attach the ContextMenuStrip when items get selected and detach it when they are unselected. 如果第一个解决方案不可接受,我想我会尝试在选择项目时附加ContextMenuStrip,并在取消选择项目时将其分离。

   Private Sub ListView1_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ListView1.MouseUp
        If e.Button = MouseButtons.Right And ListView1.SelectedItems.Count > 0 Then
            Dim cn As New ContextMenuStrip()
            cn.Items.Add("Apple")
            Me.ListView1.ContextMenuStrip = cn
            cn.Show(Control.MousePosition.X, Control.MousePosition.Y)
        End If
    End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM