【问题标题】:Menu Strip items enabling in runtime在运行时启用的菜单条项目
【发布时间】:2019-11-29 15:54:50
【问题描述】:

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

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# winforms menustrip


【解决方案1】:

我建议使用一些Extension Methods 来:

  • 获取MenuStripToolStripContextMenuStripStatusStrip 的所有后代(孩子、孩子的孩子...)
  • 获取项目的所有后代
  • 获取一个项目及其所有后代

后代扩展方法

以下扩展方法适用于 MenuStripToolStripContextMenuStripStatusStrip

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

示例

  • 禁用特定项目的所有后代:

    fileToolStripMenuItem.Descendants().ToList()
        .ForEach(x => {
            x.Enabled = false;
        });
    
  • 禁用菜单条的所有后代:

    menuStrip1.Descendants().ToList()
        .ForEach(x => {
            x.Enabled = false;
        });
    

【讨论】:

  • Mohan,如果您对扩展方法有任何困惑,请查看C# Extension Methods,如果您在应用解决方案时遇到任何困难,请告诉我。这是您可以用于满足此类要求的最通用的解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-22
  • 2012-10-22
相关资源
最近更新 更多