如果我在菜单树的不同区域运行代码,我只得到一个元素,你如何首先将此逻辑应用于菜单树的所有子组件,其次,说明整个菜单树。
我拥有的代码仅显示每个区域应用的一个阶段。
MessageBox.Show((ToolStripMenuItem).ToString());
因此,上面的内容只会显示“文件”、“保存”或“打开”,而不是“文件打开”或“文件保存”。
我是否应该在我的toolstripmenuitems中使用foreach?
如果我在菜单树的不同区域运行代码,我只得到一个元素,你如何首先将此逻辑应用于菜单树的所有子组件,其次,说明整个菜单树。
我拥有的代码仅显示每个区域应用的一个阶段。
MessageBox.Show((ToolStripMenuItem).ToString());
因此,上面的内容只会显示“文件”、“保存”或“打开”,而不是“文件打开”或“文件保存”。
我是否应该在我的toolstripmenuitems中使用foreach?
假设我有一个名为fileToolStripMenuItem
(文本为File
)的ToolStripMenuItem
,它有子项New
和Open
。此外,Open
还有From file
和Recent
。要访问所有File
的ToolStripMenuItems
(它的子级),您需要递归方法,遍历所有级别(以访问子级,孙级...)。
private IEnumerable<ToolStripMenuItem> GetChildToolStripItems(ToolStripMenuItem parent)
{
if (parent.HasDropDownItems)
{
foreach (ToolStripMenuItem child in parent.DropDownItems)
{
yield return child;
foreach (var nextLevel in GetChildToolStripItems(child))
{
yield return nextLevel;
}
}
}
}
IEnumerable<ToolStripMenuItem>
,你可以通过迭代来获取名称、更改某些属性等。使用方法如下:var list = GetChildToolStripItems(fileToolStripMenuItem);
New, Open, From File, Recent
。MessageBox
中),如下所示:MessageBox.Show(string.Join(", ", list.Select(x=>x.Text).ToArray()))
。
foreach (ToolStripMenuItem menuItem in list)
{
MessageBox.Show(string.Format("item named: {0}, with text: {1}", menuItem.Name, menuItem.Text));
}
编辑: 在看到评论后,我发现OP的想法是获取MenuStrip
中的所有项,这里提供一个示例。
我编写了一个额外的方法,以MenuStrip
为参数,遍历所有ToolStripMenuItems
,并为每个项调用GetChildToolStripItems
方法。返回所有顶级项、子项和孙子项的列表...
private List<ToolStripMenuItem> GetAllMenuStripItems(MenuStrip menu)
{
List<ToolStripMenuItem> collection = new List<ToolStripMenuItem>();
foreach (ToolStripMenuItem item in menu.Items)
{
collection.Add(item);
collection.AddRange(GetChildToolStripItems(item));
}
return collection;
}
使用方法:
var allItems = GetAllMenuStripItems(menuStrip1)
ToolStripMenuItem ThisMenuItem = (ToolStripMenuItem)sender;
string WhatClicked = ThisMenuItem.ToString();
ToolStripMenuItem ThisMenuItemOwnerItem = (ToolStripMenuItem)(ThisMenuItem.GetCurrentParent() as ToolStripDropDown).OwnerItem;
然后你可以显然地更深入地了解
ToolStripMenuItem ThisOwnersOwnerItem = (ToolStripMenuItem)(ThisMenuItemOwnerItem.GetCurrentParent() as ToolStripDropDown).OwnerItem;
等等,添加检查以避免空异常。
MenuTreeToolStripMenuItem
是什么类型? - Uwe Keim