在我的 WPF 应用程序中有一些案例要求我在给定的用户控件中找到特定类型的用户控件。例如,我有以下已经很好用的方法:
public static System.Windows.Controls.CheckBox FindChildCheckBox(DependencyObject d)
{
try
{
System.Windows.Controls.CheckBox chkBox = d as System.Windows.Controls.CheckBox;
if (d != null && chkBox == null)
{
int count = System.Windows.Media.VisualTreeHelper.GetChildrenCount(d);
for (int i = 0; i < count; i++)
{
chkBox = FindChildCheckBox(System.Windows.Media.VisualTreeHelper.GetChild(d, i));
if (chkBox != null)
break;
}
}
return chkBox;
}
catch
{
return null;
}
}
此方法将帮助我在给定的 ListViewItem 中找到 CheckBox,这使我可以更方便地选中/取消选中所述 CheckBox。
但是,我希望这种方法更通用,例如:
public static T FindChildUserControl<T>(DependencyObject d)
不幸的是,我不知道如何才能完成这项工作。有人可以帮忙吗?