簡體   English   中英

在運行時啟用的菜單條項目

[英]Menu Strip items enabling in runtime

我的菜單條如下所示。
在此處輸入圖像描述 在加載時間時,我想使啟用和可見屬性為真。 下面是我的代碼,但沒有在打印選項下使用預覽和打印選項。

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

我建議使用一些擴展方法來:

  • 獲取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; });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM