【问题标题】:How to get dynamically created ToolStripMenuItem by name in a Windows application?如何在 Windows 应用程序中按名称动态创建 ToolStripMenuItem?
【发布时间】:2018-12-22 08:13:24
【问题描述】:

表格2:

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

表格1:

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

【问题讨论】:

    标签: c# .net windows winforms


    【解决方案1】:

    你可以这样删除它:

    mHelp.DropDownItems.RemoveByKey("apProposToolStripMenuItem");
    

    你也可以这样直接删除:

    var about = mHelp.DropDownItems["apProposToolStripMenuItem"]
    mHelp.DropDownItems.Remove(about);
    

    【讨论】:

    • 谢谢兄弟.. 但是 mHelp 是第二种形式,首先我进入 form1 那个 mHelp 怎么样?
    • 在您的代码中,mHelp 是私有的。您必须将其公开,然后通过对 Form2 的引用访问它。
    【解决方案2】:

    假设您可以访问表单上的MenuStripToolStrip,那么您可以使用Descendants 扩展方法来查找所有项目,而不管其在菜单层次结构及其父项目中的位置。例如:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-31
      • 1970-01-01
      • 1970-01-01
      • 2013-11-21
      相关资源
      最近更新 更多