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; }
标签:控件,parent,childName,获取,名字,child,null,foundChild From: https://www.cnblogs.com/LXLR/p/18560969