【问题标题】:C#: How to add a full ContextMenu to MenuItem as a submenuC#:如何将完整的 ContextMenu 作为子菜单添加到 MenuItem
【发布时间】:2011-01-27 15:11:40
【问题描述】:

使用 .NET 和 Windows 窗体:

将完整的ContextMenu 添加到MenuItem 的最佳方法是什么?

我的意思是:

private void AddSubMenu(MenuItem item, ContextMenu menu)
{
   // I want to add the full menu to the menu item as a submenu

   // I could iterate the items of the menu and add them to the item
   // but I guess that there is a smarter way to do this
}

提前致谢。

【问题讨论】:

    标签: c# .net winforms user-interface


    【解决方案1】:

    其实很简单:

    private void AddSubMenu(MenuItem item, ContextMenu contextMenu)
    {
        item.MergeMenu(contextMenu);
    }
    

    显然,在合并之前订阅的所有事件处理程序仍然有效,并且会被两个菜单触发。

    【讨论】:

    • 我认为这会将上下文菜单附加到菜单而不是将其添加为子菜单。
    • 不,它将所有ContextMenu 项添加到MenuItem 下。我已经测试过了。
    【解决方案2】:

    嗯,我没有找到比迭代策略更聪明的方法。但是,您可以将其留给AddRange 函数。这样你的代码就变成了。

    private void AddSubMenu(MenuItem item, ContextMenu menu)
    {
        item.MenuItems.AddRange(menu.MenuItems);
    }
    

    MenuItems 返回一个 MenuItemCollection 并且 Addrange 采用这样的 Collection ,因此我们都感到满意,并且我们可以避免做迭代的事情。

    【讨论】:

    • 这不会编译。我正在使用 .NET 1.4 是的,我生活在旧石器时代;-)。似乎无法将 ManuItemCollection 转换为数组:(1497): Argument '1': cannot convert from 'System.Windows.Forms.Menu.MenuItemCollection' to 'System.Windows.Forms.MenuItem[]'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-04
    • 1970-01-01
    • 1970-01-01
    • 2011-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多