泛型得到界面元素

///
        /// Gets parent in visual tree.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static T GetVisualParent<T>(DependencyObject obj) where T : DependencyObject
        {
            DependencyObject parent = obj;
            while (true)
            {
                if (parent == null) return null;
                T t = parent as T;
                if (t != null) return t;
                parent = VisualTreeHelper.GetParent(parent);
            }
        }






        /// <summary>
        /// Gets children in visual tree.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static ReadOnlyCollection<T> GetVisualChildren<T>(DependencyObject obj) where T : DependencyObject
        {
            List<T> list = new List<T>();
            int count = VisualTreeHelper.GetChildrenCount(obj);
            for (int i = 0; i < count; i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(obj, i);
                if (child is T) list.Add((T)child);
                list.AddRange(GetVisualChildren<T>(child));
            }
            return new ReadOnlyCollection<T>(list);
        }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章