如何在 C# 中向 MenuStrip 的 ToolStripMenuItem 添加子项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13721627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Add Sub Items to a MenuStrip's ToolStripMenuItem in C#
提问by Learner
I have added a menustrip1into my windows form and I statically added one toolstripmenuitem(WindowstoolStripmenuItem) to that menustrip1.
And I have created a toolstripmenuitem dynamically. I want to add this dynamic toolstripmenuitem to the static menustripitem(WindowstoolStripmenuItem) which is created statically on design time.
我已经menustrip1在我的 Windows 窗体中添加了一个,并且我静态地添加了一个toolstripmenuitem(WindowstoolStripmenuItem) 到那个menustrip1. 我已经动态创建了一个工具条菜单项。我想将此动态工具条菜单项添加到在设计时静态创建的静态菜单条项(WindowstoolStripmenuItem)中。
ToolStripMenuItem itm = new ToolStripMenuItem();
itm.Name = "fm1";
itm.Text = "Form1";
How can I add this subitem to the static menustrip's Windows item.
如何将此子项添加到静态菜单条的 Windows 项中。
采纳答案by Jürgen Steinblock
You can add a ToolStripMenuItemto another ToolStripMenuItem.DropDownItemscollection.
您可以将一个添加ToolStripMenuItem到另一个ToolStripMenuItem.DropDownItems集合。
If you don't have a reference to your ToolStripMenuItem, you can get one by key (Name Property) or Index
如果您没有对 ToolStripMenuItem 的引用,则可以通过键(名称属性)或索引获取
var itm = menustrip1.Items["Text"];
var itm = menustrip1.Items[0];
Here is the code
这是代码
var menustrip1 = new System.Windows.Forms.MenuStrip();
var item = new System.Windows.Forms.ToolStripMenuItem()
{
Name = "Test",
Text = "Test"
};
var item2 = new System.Windows.Forms.ToolStripMenuItem()
{
Name = "Test",
Text = "Test"
};
item.DropDownItems.Add(item2);
menustrip1.Items.Add(item);

