如何在contextmenustrip上添加subitem上的事件? C#

时间:2011-05-06 09:05:47

标签: c# contextmenu

for (int i = 0; i < client.Folders.Count; i++)
        {

            (ContextMenuListView.Items[1] as ToolStripMenuItem).DropDownItems.Add(client.Folders[i].Name);//add Folder to Move To
            (ContextMenuListView.Items[2] as ToolStripMenuItem).DropDownItems.Add(client.Folders[i].Name);                
        }

如何在Items [1]或Items [2]中获取子项目?

1 个答案:

答案 0 :(得分:1)

ToolStripItemCollection.Add(string)(DropDownItems.Add())将返回新的ToolStripItem ...

另一方面,ToolStripItemCollection DropDownItems

引用了所有其他子项

因此,获取两个创建项目的简便方法是:

(ContextMenuListView.Items[1] as ToolStripMenuItem).DropDownItems.Add(client.Folders[i].Name);
(ContextMenuListView.Items[2] as ToolStripMenuItem).DropDownItems.Add(client.Folders[i].Name);

会变成:

ToolStripItem firstItem = (ContextMenuListView.Items[1] as ToolStripMenuItem).DropDownItems.Add(client.Folders[i].Name);
ToolStripItem secondItem = (ContextMenuListView.Items[2] as ToolStripMenuItem).DropDownItems.Add(client.Folders[i].Name);

或访问所有子项:

foreach(ToolStripItem i in (ContextMenuListView.Items[1] as ToolStripMenuItem).DropDownItems.OfType<ToolStripItem>())
{
   //...
}

或访问特定子项:

var specificItem = (ContextMenuListView.Items[1] as ToolStripMenuItem).DropDownItems.Item[0];