我已经尝试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));
}
}
但我只获得File
,Edit
,View
我需要触及Export
(参见图)及其subitem
,并可能更改Word
的可见度。
注意:form
动态更改menustrip
项,这就是我需要循环播放它们的原因。
答案 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));
}