每次的foreach在子项目将MenuStrip [英] Foreach every Subitem in a MenuStrip
本文介绍了每次的foreach在子项目将MenuStrip的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想获得所有的子项目
我的的MenuStrip
,所以我可以一次改变它们。
我'尝试的东西像下面,但他们没有工作:
的foreach(ToolStripMenuItem toolItem在menuStrip1.DropDownItems)
{
//使用toolItem的东西在这里
}
有人能帮助我的编码一个很好的 foreach循环
获取所有的 SubMenuItems(DropDownItems)
从的MenuStrip
?
编辑现在想用下面的<$ C工作$ C>递归方法:
私人无效SetToolStripItems(ToolStripItemCollection dropDownItems)
{
试
{
的foreach(在dropDownItems obj对象)
{
如果(obj.GetType()。等于(typeof运算(ToolStripMenuItem)))
{
ToolStripMenuItem子菜单=(ToolStripMenuItem)目标文件;
如果(subMenu.HasDropDownItems)
{
SetToolStripItems(subMenu.DropDownItems);
}
,否则
{
}
}
}
}
抓
{
}
}
解决方案
试试这个:
列表< ToolStripMenuItem> allItems =新的List< ToolStripMenuItem>();
的foreach(ToolStripMenuItem toolItem在menuStrip.Items)
{
allItems.Add(toolItem);
//加分项目
allItems.AddRange(GetItems(toolItem));
}
私人的IEnumerable< ToolStripMenuItem> GetItems(ToolStripMenuItem项目)
{
的foreach(ToolStripMenuItem dropDownItem在item.DropDownItems)
{
如果(dropDownItem.HasDropDownItems)
{
的foreach(ToolStripMenuItem分项中GetItems(dropDownItem))
收益率的回报子项目;
}
收益率的回报dropDownItem;
}
}
I want to get all the SubItems
of my MenuStrip
, So I can change them all at once.
I'am trying things like the following, but they aren't working:
foreach (ToolStripMenuItem toolItem in menuStrip1.DropDownItems)
{
//Do something with toolItem here
}
Can someone help me out coding a good foreach loop
for getting all the SubMenuItems(DropDownItems)
from the MenuStrip
?
EDIT now trying to work with the following 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
{
}
}
解决方案
Try this:
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;
}
}
这篇关于每次的foreach在子项目将MenuStrip的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文