C# 循环遍历menustrip中的子项

C# 循环遍历menustrip中的子项,c#,menustrip,C#,Menustrip,我试过: private IEnumerable GetItems(ToolStripMenuItem项目) { foreach(item.DropDownItems中的ToolStripMenuItem dropDownItem) { if(dropDownItem.HasDropDownItems) { foreach(GetItems中的ToolStripMenuItem子项(dropDownItem)) 收益回报子项; } 收益率返回下拉项; } } 私有无效按钮2\u单击\u 1(对象

我试过:

private IEnumerable GetItems(ToolStripMenuItem项目)
{
foreach(item.DropDownItems中的ToolStripMenuItem dropDownItem)
{
if(dropDownItem.HasDropDownItems)
{
foreach(GetItems中的ToolStripMenuItem子项(dropDownItem))
收益回报子项;
}
收益率返回下拉项;
}
}
私有无效按钮2\u单击\u 1(对象发送者,事件参数e)
{
列表所有项=新列表();
foreach(menuStrip1.Items中的ToolStripMenuItem toolItem)
{
添加(工具项);
MessageBox.Show(toolItem.Text);
allItems.AddRange(GetItems(toolItem));
}
}
但是我只得到
文件
编辑
查看

我需要访问
Export
(见图)及其
子项
,例如,可能会更改
Word
的可见性


注意:
表单
动态更改
菜单项
这就是我需要循环查看它们的原因。

根据您提供的详细信息,您可以将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
    }
}
希望这能对你有所帮助


关于

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

//获取所有顶部菜单项,例如文件、编辑和查看
列表所有项=新列表();
foreach(menuStrip1.Items中的ToolStripMenuItem项)
{
//对于每个顶部菜单项,递归获取所有子项
allItems.AddRange(GetItems(item));
}

嗯,我无法测试它,在
项下有一条蓝线。Text
项。Visible
“对象不包含文本的定义,Visible…”这是因为编译器不知道foreach循环中的项的类型,而不是(var项)put(ToolStripItem项)并给它一个tryterrable post。方法
GetItems
不存在
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
    }
}
// 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)); 
}