public static T FindChild<T>(DependencyObject parent, string childName) where T : DependencyObject
{
// 检查null情况
if (parent == null) return null;
T foundChild = null;
int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < childrenCount; i++)
{
DependencyObject child = VisualTreeHelper.GetChild(parent, i);
// 如果类型匹配并且名称(如果提供)也匹配
if (child != null && child is T && child.GetValue(NameProperty).ToString() == childName)
{
// 如果找到匹配项,则返回
foundChild = (T)child;
break;
}
else
{
// 否则,递归查找
foundChild = FindChild<T>(child, childName);
if (foundChild != null)
{
break;
}
}
}
return foundChild;
}