如何根据子控件名字获取子控件

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;
        }

 

posted @ 2024-11-21 16:02  LXLR  阅读(6)  评论(0编辑  收藏  举报