我想获取我的SubItems的所有MenuStrip,所以我可以一次更改它们。

我正在尝试以下操作,但是它们没有用:

foreach (ToolStripMenuItem toolItem in menuStrip1.DropDownItems)
{
      //Do something with toolItem here
}

有人可以帮我编码一个好的foreach loop以便从SubMenuItems(DropDownItems)中获取所有MenuStrip吗?

现在,EDIT尝试使用以下Recursive method:
private void SetToolStripItems(ToolStripItemCollection dropDownItems)
        {
            try
            {
                foreach (object obj in dropDownItems)
                {
                    if (obj.GetType().Equals(typeof(ToolStripMenuItem)))
                    {
                        ToolStripMenuItem subMenu = (ToolStripMenuItem)obj;

                        if (subMenu.HasDropDownItems)
                        {
                            SetToolStripItems(subMenu.DropDownItems);
                        }
                        else
                        {

                        }
                    }
                }
            }
            catch
            {

            }
        }

最佳答案

试试这个:

List<ToolStripMenuItem> allItems = new List<ToolStripMenuItem>();
foreach (ToolStripMenuItem toolItem in menuStrip.Items)
{
    allItems.Add(toolItem);
    //add sub items
    allItems.AddRange(GetItems(toolItem));
}
private IEnumerable<ToolStripMenuItem> GetItems(ToolStripMenuItem item)
{
    foreach (ToolStripMenuItem dropDownItem in item.DropDownItems)
    {
        if (dropDownItem.HasDropDownItems)
        {
            foreach (ToolStripMenuItem subItem in GetItems(dropDownItem))
                yield return subItem;
        }
        yield return dropDownItem;
    }
}

关于c# - 遍历MenuStrip中的每个子项,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15380730/

10-12 20:27