1

我有一个上下文菜单条,其中将根据特定条件填充菜单项。

前任:

对于条件1:

myContextMenuStrip.Items.Clear();
myContextMenuStrip.Items.Add("Item title", null, myClickHandler);
myContextMenuStrip.Items.Add("Item Status", null, myClickHandler);
myContextMenuStrip.Items.Add("Item Variables", null, myClickHandler);

条件2:

myContextMenuStrip.Items.Clear();
myContextMenuStrip.Items.Add("Item Status", null, myClickHandler);

对于条件1,我使用向 ItemStatus 添加子菜单

(myContextMenuStrip.Items[1] as ToolStripMenuItem).DropDownItems.Add("Submenu1", null, new EventHandler(gridcontextsubMenu_ItemClicked));
(myContextMenuStrip.Items[1] as ToolStripMenuItem).DropDownItems.Add("Submenu2", null, new EventHandler(gridcontextsubMenu_ItemClicked));

对于 condition2 向 ItemStatus 添加子菜单,我使用

(myContextMenuStrip.Items[0] as ToolStripMenuItem).DropDownItems.Add("Submenu1", null, new EventHandler(gridcontextsubMenu_ItemClicked));
(myContextMenuStrip.Items[0] as ToolStripMenuItem).DropDownItems.Add("Submenu2", null, new EventHandler(gridcontextsubMenu_ItemClicked));

但我需要一种将子菜单添加到菜单项 ItemStatus 的通用方法。

欢迎分享答案

4

1 回答 1

2

a的Items属性ContextMenuStrip返回 a ToolStripItemCollection,它允许您使用带有索引号或名称的索引器。因此,您可以将项目名称用于Items. 例如:

(myContextMenuStrip.Items["Item Status"] as ToolStripMenuItem).DropDownItems.Add("Submenu1", null, new EventHandler(gridcontexsubMenu_ItemClicked));
于 2012-12-06T10:20:12.350 回答