在menustrip中循环子项目

时间:2014-02-25 13:02:10

标签: c# menustrip

我已经尝试this

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;
    }
}

private void button2_Click_1(object sender, EventArgs e)
{
    List<ToolStripMenuItem> allItems = new List<ToolStripMenuItem>();
    foreach (ToolStripMenuItem toolItem in menuStrip1.Items)
    {
        allItems.Add(toolItem);
        MessageBox.Show(toolItem.Text);
        allItems.AddRange(GetItems(toolItem));
    }
}

但我只获得FileEditView

enter image description here

我需要触及Export(参见图)及其subitem,并可能更改Word的可见度。

注意:form动态更改menustrip项,这就是我需要循环播放它们的原因。

2 个答案:

答案 0 :(得分:4)

根据您提供的详细信息,您可以使用linq作为

var exportMenu=allItems.FirstOrDefault(t=>t.Text=="Export");
if(exportMenu!=null)
{
    foreach(ToolStripItem item in exportMenu.DropDownItems) // here i changed the var item to ToolStripItem
    {
         if(item.Text=="Word") // as you mentioned in the requirements
              item.Visible=false; // or any variable that will set the visibility of the item
    }
}

希望这会对你有所帮助

问候

答案 1 :(得分:0)

为了获取MenuStrip中的所有菜单项(ToolStripMenuItem实例),请使用以下代码(我假设MenuStrip名称为menuStrip1)

// Get all the top menu items, e.g. File , Edit and View
List<ToolStripMenuItem> allItems = new List<ToolStripMenuItem>();
foreach (ToolStripMenuItem item in menuStrip1.Items)
{
   // For each of the top menu items, get all sub items recursively
    allItems.AddRange(GetItems(item)); 
}