C# ContextMenuStrip 动态添加子项
我想要用代码 在菜单的"e"子项中再插入一个子项"h"
可是我用ContextMenuStrip.Items["a"].
点不出另一个Item[]了,怎样才能访问到ContextMenuStrip->a->e 这个项并且调用add方法添加 "h" 呢?
解决了追加分 展开
你需要把ToolStripMenuItem强制转换为ToolStripDropDownItem类型才能添加子项,其实你自己看看Form1.Designer.cs里设计器自动生成的代码就会明白了,方法如下
private void button1_Click(object sender, EventArgs e)
{
((ToolStripDropDownItem)(((ToolStripDropDownItem)contextMenuStrip1.Items["aToolStripMenuItem"]).DropDownItems["eToolStripMenuItem"])).DropDownItems.Add(new ToolStripMenuItem("h"));
//或者
ToolStripDropDownItem ts = ((ToolStripDropDownItem)contextMenuStrip1.Items["aToolStripMenuItem"]);
ts = ((ToolStripDropDownItem)ts.DropDownItems["eToolStripMenuItem"]);
ts.DropDownItems.Add(new ToolStripMenuItem("h"));
}
添加一个菜单的代码:
this.ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
private System.Windows.Forms.ToolStripMenuItem ToolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem ToolStripMenuItem2;
private System.Windows.Forms.ToolStripMenuItem ToolStripMenuItem3;
this.ToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.ToolStripMenuItem1});
this.ToolStripMenuItem.Name = "ToolStripMenuItem";
this.ToolStripMenuItem.Size = new System.Drawing.Size(23, 20);
this.ToolStripMenuItem.Text = "A";//第一级
this.ToolStripMenuItem1.Click += new System.EventHandler(this.ToolStripMenuItem1_Click)
this.工ToolStripMenuItem1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.ToolStripMenuItem2});
this.ToolStripMenuItem1.Name = "ToolStripMenuItem1";
this.ToolStripMenuItem1.Size = new System.Drawing.Size(152, 22);
this.ToolStripMenuItem1.Text = "B";//第二级
this.ToolStripMenuItem2.Click += new System.EventHandler(this.ToolStripMenuItem2_Click)
this.ToolStripMenuItem2.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.ToolStripMenuItem3});
this.ToolStripMenuItem2.Name = "ToolStripMenuItem2";
this.ToolStripMenuItem2.Size = new System.Drawing.Size(152, 22);
this.工ToolStripMenuItem2.Text = "C";//第三级
this.ToolStripMenuItem3.Click += new System.EventHandler(this.ToolStripMenuItem3_Click)