wpf 查找指定类型的子元素

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

posted on 2022-12-07 17:23  wu.g.q  阅读(52)  评论(0编辑  收藏  举报

导航