簡體   English   中英

如何隱藏窗體中的所有面板?

[英]how to hide all panels in windows form?

在我的使用菜單條和多個面板容器的Windows應用程序中,根據菜單選項顯示一個面板

通過手動傳遞名稱隱藏所有面板是非常耗時的,有沒有辦法隱藏所有面板或任何方式來獲取表單中所有面板的名稱?

foreach (Control c in this.Controls)
{
    if (c is Panel) c.Visible = false;
}

你甚至可以使它遞歸,並傳入ControlCollection而不是使用this.Controls

HidePanels(this.Controls);

...

private void HidePanels(ControlCollection controls)
{
    foreach (Control c in controls)
    {
        if (c is Panel)
        {
            c.Visible = false;
        }

        // hide any panels this control may have
        HidePanels(c.Controls);
    }
}

因此,您可能希望獲得表單上任何位置的所有控件,而不僅僅是頂級控件。 為此,我們需要這個方便的小助手函數來獲取特定控件的所有級別的所有子控件:

public static IEnumerable<Control> GetAllControls(Control control)
{
    Stack<Control> stack = new Stack<Control>();
    stack.Push(control);

    while (stack.Any())
    {
        var next = stack.Pop();
        yield return next;
        foreach (Control child in next.Controls)
        {
            stack.Push(child);
        }
    }
}

(如果你認為你已經足夠使用它,請隨意將它作為一種擴展方法。)

然后我們可以在該結果上使用OfType來獲取特定類型的控件:

var panels = GetAllControls(this).OfType<Panel>();

它寫得像這樣干凈

foreach (Panel p in this.Controls.OfType<Panel>()) {
    p.Visible = false;
}

哎呀! 我也只是編寫代碼! :P

Control[] aryControls = new Control[]{ controlnamehere1, controlnamehere2 };
foreach (Control ctrl in aryControls)
{
   ctrl.Hide();
}

或者,或者:

Control[] aryControls = new Control[]{ controlnamehere1, controlnamehere1 };
foreach (Control ctrl in aryControls)
{
   ctrl.Visible = false;
}

暫無
暫無

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

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