Menu Strip items enabling in runtime

夙愿已清 提交于 2019-12-11 16:56:13

问题


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


来源:https://stackoverflow.com/questions/53812556/menu-strip-items-enabling-in-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!