c# - 运行时启用的菜单条项目
问题描述
我的菜单条如下所示。
在加载时间时,我想为启用和可见属性设置为真。下面是我的代码,但没有在打印选项下使用预览和打印选项。
foreach (ToolStripMenuItem i in menuStrip.Items)
{
for (int x = 0; x <= i.DropDownItems.Count-1; x++)
{
i.DropDownItems[x].Visible = true;
i.DropDownItems[x].Enabled = true;
}
i.Available = true;
i.Visible = true;
i.Enabled = true;
}
解决方案
I'd suggest using some Extension Methods to:
- Get all descendants (children, children of children, ...) fo a
MenuStrip
,ToolStrip
orContextMenuStrip
orStatusStrip
- Get all descendants of an item
- Get an item and all of its descendants
Descendants Extension Methods
The following extension methods will work for a MenuStrip
, ToolStrip
, ContextMenuStrip
or 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;
}
}
}
Example
Disable all descendants of a specific item:
fileToolStripMenuItem.Descendants().ToList() .ForEach(x => { x.Enabled = false; });
Disable all descendants of the menu strip:
menuStrip1.Descendants().ToList() .ForEach(x => { x.Enabled = false; });
推荐阅读
- python - PyOpenGL 读回缓冲区颜色
- git - 如何让 git diff 列出自上次提交以来创建的 * 文件?
- python - 由于 Google Colab,在 VS Code 上使用 Jupyter notebook 时无法连接到内核。它已被卸载,但仍然无法连接到内核
- firebase-realtime-database - Firebase 规则:仅针对一个用户 uid 在特定节点上启用写入
- reactjs - Heroku 部署与反应
- mysql - 替换字符顺序 MySQL 字段
- c - C程序中scanf和printf中奇怪的换行问题
- python - Python根据另一个数据框中的列值匹配列名
- r - 根据R中的表格生成重复字符的字符串
- javascript - 防止在 href="#" 链接中滚动到顶部