您將需要使用遞歸。以下是使用擴展方法的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添加到我們的Form中。
我相信你也不應該有太多問題converting it to VB.NET ...另外,如果你不想要「keepApplyingForever」功能,它應該很容易去除。
的可能的複製[如何獲得一個Windows的所有子控件形成了一個特定的類型(按鈕/文本框)的形式?(https://stackoverflow.com/questions/3419159/how-to-get - 全兒童控制對的一 - 窗口表單的形式對的一特定類型的按鈕) – PulseJet 2017-06-22 05:18:48