在我的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;
}