我有一个窗体 MainForm
,它是一个包含许多子控件的 Windows 窗体窗体。我想在 MainForm
上调用一个函数来通知它的所有子级。 Windows 窗体窗体是否提供了执行此操作的方法?我玩过更新、刷新和无效,但没有成功。
最佳答案
foreach (Control ctrl in this.Controls)
{
// call whatever you want on ctrl
}
如果您想访问窗体上的所有控件,以及窗体上每个控件的所有控件(以此类推,递归地),请使用如下函数:
public void DoSomething(Control.ControlCollection controls)
{
foreach (Control ctrl in controls)
{
// do something to ctrl
MessageBox.Show(ctrl.Name);
// recurse through all child controls
DoSomething(ctrl.Controls);
}
}
...您通过最初传入表单的 Controls 集合来调用它,如下所示:
DoSomething(this.Controls);
关于c# - 通过 C# 递归通知子控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1418018/