C#为什么我不能在ToolStripMenuItem中获得带有子菜单项的菜单项?

时间:2017-12-21 12:31:07

标签: c# items toolstripmenu

想要创建菜单和子菜单(还有点击事件),但是无法找出如何在DropDownItems中插入已创建的对象? 当我插入注释代码时 - 总是只在最后一个菜单上获取所有子项,其他没有它。

    private System.Windows.Forms.ToolStripDropDownButton tlsDropDown;

    List<ToolStripMenuItem> ToolStripListForInsert = new List<ToolStripMenuItem>() 
    {
        new ToolStripMenuItem("Erase"), new ToolStripMenuItem("Change"), new ToolStripMenuItem("NewChange")
    };

    for (int i = 0; i < 10; i++)
    {
        tlsDropDown.DropDownItems.Add(new ToolStripMenuItem("NewItem", null, new ToolStripMenuItem("Erase"), new ToolStripMenuItem("Change"), new ToolStripMenuItem("NewChange")));

        // why this don't work - for all menu items --- work only for last one
        /*tlsDropDown.DropDownItems.Add(new ToolStripMenuItem(names[i], null, ToolStripListForInsert.ToArray()));*/
    }

1 个答案:

答案 0 :(得分:1)

正如有人已经提到的那样,你不能将ToolStripItem的同一个实例添加到多个(子)菜单中。

您可以通过为每个父项创建ToolStripItem的新实例来使代码工作。

例如,这应该起作用:

private System.Windows.Forms.ToolStripDropDownButton tlsDropDown;

for (int i = 0; i < 10; i++)
{
    //tlsDropDown.DropDownItems.Add(new ToolStripMenuItem("NewItem", null, new ToolStripMenuItem("Erase"), new ToolStripMenuItem("Change"), new ToolStripMenuItem("NewChange")));

    List<ToolStripMenuItem> ToolStripListForInsert = new List<ToolStripMenuItem>() 
    {
        new ToolStripMenuItem("Erase"), new ToolStripMenuItem("Change"), new ToolStripMenuItem("NewChange")
    };

    tlsDropDown.DropDownItems.Add(new ToolStripMenuItem(names[i], null, ToolStripListForInsert.ToArray()));
}