如何在Windows应用程序中按名称获取动态创建的ToolStripMenuItem?

时间:2018-12-22 08:13:25

标签: c# .net windows winforms

Form2:

private ToolStripMenuItem mHelp;
private ToolStripMenuItem apProposToolStripMenuItem;
public void intializecomponent()
{
this.mHelp = new ToolStripMenuItem();
      this.contentsToolStripMenuItem = new ToolStripMenuItem();
      this.apProposToolStripMenuItem = new ToolStripMenuItem();
     this.mHelp.DropDownItems.AddRange(new ToolStripItem[2]
          {
            (ToolStripItem) this.contentsToolStripMenuItem,
            (ToolStripItem) this.apProposToolStripMenuItem
          });
          this.mHelp.Name = "mHelp";
          this.mHelp.Size = new Size(44, 20);
          this.mHelp.Text = "Help";
          this.contentsToolStripMenuItem.Name = "contentsToolStripMenuItem";
          this.contentsToolStripMenuItem.Size = new Size(122, 22);
          this.contentsToolStripMenuItem.Text = "Contents";
          this.contentsToolStripMenuItem.Click += new EventHandler(this.contentsToolStripMenuItem_Click);
          this.apProposToolStripMenuItem.Image = (Image) componentResourceManager.GetObject("apProposToolStripMenuItem.Image");
          this.apProposToolStripMenuItem.Name = "apProposToolStripMenuItem";
          this.apProposToolStripMenuItem.Size = new Size(122, 22);
          this.apProposToolStripMenuItem.Text = "About";
          this.apProposToolStripMenuItem.Click += new EventHandler(this.apProposToolStripMenuItem_Click);
    this.Load += new EventHandler(this.DocumentSpace_Load);
}

如何在表单上找到apProposToolStripMenuItem?我试图删除一个特定的ToolStripMenuItem,但是它不起作用并且找不到apProposToolStripMenuItem

Form1:

ToolStripMenuItem mi = new ToolStripMenuItem("apProposToolStripMenuItem") { Name = "About" };
mi.DropDownItems.RemoveByKey("About");

2 个答案:

答案 0 :(得分:2)

您可以按如下名称删除它:

type /?

您也可以像这样直接将其删除:

mHelp.DropDownItems.RemoveByKey("apProposToolStripMenuItem");

答案 1 :(得分:1)

假设您有权访问表单上的MenuStripToolStrip,则可以使用Descendants扩展方法来查找所有项目,无论其在菜单和菜单层次结构中的位置如何。它的父项。例如:

var item = menuStrip1.Descendants()
    .Where(x => x.Name == "printToolStripMenuItem").FirstOrDefault();
item?.GetCurrentParent().Items.Remove(item);