首页 > 其他分享 >wpf 查找指定类型的子元素

wpf 查找指定类型的子元素

时间:2022-12-07 17:36:26浏览次数:50  
标签:GetChildObjects List 指定 childList 查找 child wpf DependencyObject

public List<T> GetChildObjects<T>(DependencyObject obj, Type typename) where T : FrameworkElement
        {
            DependencyObject child = null;
            List<T> childList = new List<T>();

            for (int i = 0; i <= VisualTreeHelper.GetChildrenCount(obj) - 1; i++)
            {
                child = VisualTreeHelper.GetChild(obj, i);

                if (child is T && (((T)child).GetType() == typename))
                {
                    childList.Add((T)child);
                }
                childList.AddRange(GetChildObjects<T>(child, typename));
            }
            return childList;
        }

使用部分:

 List<TextBlock> listTextBlock = GetChildObjects<TextBlock>(dgSimple, typeof(TextBlock));
dgSimple:父元素name

标签:GetChildObjects,List,指定,childList,查找,child,wpf,DependencyObject
From: https://www.cnblogs.com/wuguoqiang/p/16963743.html

相关文章