简体   繁体   中英

Menu Strip items enabling in runtime

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;
}

I'd suggest using some Extension Methods to:

  • Get all descendants (children, children of children, ...) fo a MenuStrip , ToolStrip or ContextMenuStrip or StatusStrip
  • 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; });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM