首页 > 解决方案 > 运行时启用的菜单条项目

问题描述

我的菜单条如下所示。
在此处输入图像描述 在加载时间时,我想为启用和可见属性设置为真。下面是我的代码,但没有在打印选项下使用预览和打印选项。

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

标签: c#winformsmenustrip

解决方案


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

推荐阅读