问题
My menu Strip is like below.
while loading time i want to make true for enable and visible property.
Below is my code but that is not taking the preview and print option under the print option.
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;
}
回答1:
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; });
来源:https://stackoverflow.com/questions/53812556/menu-strip-items-enabling-in-runtime