【问题标题】:How to add menu item dynamically during run time [closed]如何在运行时动态添加菜单项[关闭]
【发布时间】:2014-06-02 01:40:57
【问题描述】:

我可以使用以下代码执行子菜单列表:

Dim cm As GoContextMenu = New GoContextMenu(view) 'GoContextMenu  Inherits System.Windows.Forms.ContextMenu 

Dim subTop(1) As MenuItem      ' if you have 2 submenu, then the array count is 2-1 = 1; subm(1)          
Dim orMenu As New MenuItem("OR", New EventHandler(AddressOf Me.OrTopGateItem_Click))
Dim andMenu As New MenuItem("AND", New EventHandler(AddressOf Me.AndTopGateItem_Click))

cm.MenuItems.Add(New MenuItem("Type", subTop))

根据上述情况,我设法创建了一个子菜单,如下图所示: screen shot of my submenu outcome

如何在运行时动态添加更多子菜单?

谢谢。

【问题讨论】:

  • 您到底想添加什么?您不能只添加 anything,因为对于那些您不会声明处理程序。请提供更多详细信息。
  • @Neolisk,在上面的示例代码中,我需要在执行程序之前手动创建一个数组并定义大小,因为我知道菜单中的项目数。现在项目的数量在运行时是未知的,如何将这些项目动态添加到子菜单中?
  • 我仍然无法理解您的要求。你期望最终得到什么?假设其中一些在编译时已知(=它们是静态的),您将如何填充这些动态项。请出示相关代码。
  • 您的操作方式与设计时相同。请参阅下面的 MSDN 代码。

标签: vb.net time submenu


【解决方案1】:
Public Class Form1


    Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load

        Me.ContextMenuStrip = ContextMenuStrip1

        Dim menu1 As New ToolStripMenuItem() With {.Text = "Menu Item 1", .Name = "mnuItem1"}
        AddHandler menu1.Click, AddressOf mnuItem_Clicked
        ContextMenuStrip1.Items.Add(menu1)

        'Add a submenu to Menu 1
        Dim menu2 As New ToolStripMenuItem() With {.Text = "Menu Item 2", .Name = "mnuItem2"}
        'We have a reference to menu1 already, but here's how you can find the menu item by name...
        For Each item As ToolStripMenuItem In ContextMenuStrip1.Items
            If item.Name = "mnuItem1" Then
                item.DropDownItems.Add(menu2)
                AddHandler menu2.Click, AddressOf mnuItem_Clicked
            End If
        Next


    End Sub

    Private Sub mnuItem_Clicked(sender As Object, e As EventArgs)
        ContextMenuStrip1.Hide() 'Sometimes the menu items can remain open.  May not be necessary for you.
        Dim item As ToolStripMenuItem = TryCast(sender, ToolStripMenuItem)
        If item IsNot Nothing Then
            MsgBox("You've clicked " & item.Name)
        End If
    End Sub

End Class

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-26
    • 1970-01-01
    • 1970-01-01
    • 2010-09-22
    • 2013-08-20
    • 2020-09-03
    • 1970-01-01
    相关资源
    最近更新 更多