In Winforms, it is
this.Controls
but not with System.Windows.Controls.Control, which is WPF
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Dear All,
I am trying to create a BaseForm. Thus in the future, each Form project's Forms will inherit from this BaseForm. I create a method, ResizeForm, that the Resize event will call this method. This method is going to loop through all controls in the inherited form to do something.
Could anybody tell me that can the method loops through all controls?
In Winforms, it is
this.Controls
but not with System.Windows.Controls.Control, which is WPF
If there a panels or other similar containers consider the following.
public static class ControlExtensions
{
public static IEnumerable<T> Descendants<T>(this Control control) where T : class
{
foreach (Control child in control.Controls)
{
if (child is T thisControl)
{
yield return (T)thisControl;
}
if (child.HasChildren)
{
foreach (T descendant in Descendants<T>(child))
{
yield return descendant;
}
}
}
}
}
Implemented
public partial class BaseForm : Form
{
public BaseForm()
{
InitializeComponent();
Resize += OnResize;
}
private void OnResize(object sender, EventArgs e)
{
var controls = this.Descendants<Control>();
foreach (var control in controls)
{
Console.WriteLine($"{control.Parent.Name}.{control.Name}");
}
}
}