[英]Menu Strip items enabling in runtime
我建议使用一些扩展方法来:
MenuStrip
、 ToolStrip
或ContextMenuStrip
或StatusStrip
的所有后代(孩子、孩子的孩子……)后代扩展方法
以下扩展方法适用于MenuStrip
、 ToolStrip
、 ContextMenuStrip
或StatusStrip
:
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
public static class ToolStripExtensions
{
public static IEnumerable<ToolStripItem> Descendants(this ToolStrip toolStrip)
{
return toolStrip.Items.Flatten();
}
public static IEnumerable<ToolStripItem> Descendants(this ToolStripDropDownItem item)
{
return item.DropDownItems.Flatten();
}
public static IEnumerable<ToolStripItem> DescendantsAndSelf (this ToolStripDropDownItem item)
{
return (new[] { item }).Concat(item.DropDownItems.Flatten());
}
private static IEnumerable<ToolStripItem> Flatten(this ToolStripItemCollection items)
{
foreach (ToolStripItem i in items)
{
yield return i;
if (i is ToolStripDropDownItem)
foreach (ToolStripItem s in ((ToolStripDropDownItem)i).DropDownItems.Flatten())
yield return s;
}
}
}
例子
禁用特定项目的所有后代:
fileToolStripMenuItem.Descendants().ToList().ForEach(x => { x.Enabled = false; });
禁用菜单条的所有后代:
menuStrip1.Descendants().ToList().ForEach(x => { x.Enabled = false; });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.