C# WPF 查找窗体上的子元素、得到窗体上的一类元素

 /// <summary>
        /// 查找窗体上的子元素
        /// </summary>
        /// <typeparam name="T">要查找的子元素的类型</typeparam>
        /// <param name="dependencyObject">父级元素</param>
        /// <param name="name">子元素的名称</param>
        /// <returns></returns>
        public static T GetChildElement<T>(DependencyObject dependencyObject, string name) where T : FrameworkElement
        {
            DependencyObject dependencyElement = null;
            T grandChild = null;
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(dependencyObject)-1; i++)
            {
                dependencyElement = VisualTreeHelper.GetChild(dependencyObject,i);
                if (dependencyElement is T && (((T)dependencyElement).Name == name | string.IsNullOrEmpty(name)))
                {
                    return (T)dependencyElement;
                }
                else
                {
                    // 在下一级中没有找到指定名字的子控件,就再往下一级找
                    grandChild = GetChildElement<T>(grandChild, name);
                    if (grandChild != null)
                        return grandChild;
                }
            }
            return null;
        }
  #region 得到窗体上的某一类型的元素
        /// <summary>
        /// 得到窗体上的某一类型的元素
        /// </summary>
        /// <typeparam name="T">元素类型</typeparam>
        /// <param name="element">要查找的父级元素</param>
        /// <param name="typeName">类类型</param>
        /// <returns></returns>
        public static List<T> GetUIElement<T>(DependencyObject element, Type typeName) where T : FrameworkElement
        {
            DependencyObject child = null;
            List<T> childList = new List<T>();
            List<string> vs = new List<string>();
           
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++)
            {
                child = VisualTreeHelper.GetChild(element, i);
                if (child is T && (((T)child).GetType() == typeName))
                {
                    childList.Add((T)child);
                }
                childList.AddRange(GetUIElement<T>(child, typeName));
            }
            return childList;
        }
        #endregion

 

上一篇:【Flutter 专题】116 图解 PhysicalModel & PhysicalShape 裁切小组件


下一篇:vue 父子界面组件传值