您将需要使用递归。以下是使用扩展方法的 C# 解决方案,超出了您的问题范围,但我只是从我们的框架中提取了它。
static partial class ControlExtensions
{
public static void ApplyToMatchingChild(this Control parent, Action<Control> actionToApplyWhenFound, bool keepApplyingForever, params Func<Control, bool>[] matchingChildCriteria)
{
ControlEventHandler reapplyEventHandler = null;
if (keepApplyingForever)
{
reapplyEventHandler = (s, e) =>
{
ApplyToMatchingChild(e.Control, actionToApplyWhenFound, keepApplyingForever, matchingChildCriteria);
};
}
SearchForMatchingChildTypes(parent, actionToApplyWhenFound, reapplyEventHandler, matchingChildCriteria);
}
private static void SearchForMatchingChildTypes(Control control, Action<Control> actionToApplyWhenFound, ControlEventHandler reapplyEventHandler, params Func<Control, bool>[] matchingChildCriteria)
{
if (matchingChildCriteria.Any(criteria => criteria(control)))
{
actionToApplyWhenFound(control);
}
if (reapplyEventHandler != null)
{
control.ControlAdded += reapplyEventHandler;
}
if (control.HasChildren)
{
foreach (var ctl in control.Controls.Cast<Control>())
{
SearchForMatchingChildTypes(ctl, actionToApplyWhenFound, reapplyEventHandler, matchingChildCriteria);
}
}
}
}
然后调用:
myControl.ApplyToMatchingChild(c => { /* Do Stuff to c */ return; }, false, c => c is TextBox);
这将对所有子文本框应用一个函数。您可以使用keepApplyingForever 参数来确保在以后添加子控件时应用您的函数。该函数还允许您指定任意数量的匹配条件,例如,如果控件也是标签或其他一些条件。
我们实际上使用它作为一种简洁的方式来调用我们的依赖注入容器,以便为每个添加到表单的 UserControl。
我相信converting it to VB.NET 也不应该有太多问题...此外,如果您不想要“keepApplyingForever”功能,也应该很容易去掉它。