public List<T> GetChildObjects<T>(DependencyObject obj, string name) 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).Name == name || string.IsNullOrEmpty(name)))
                {
                    childList.Add((T)child);
                }
                childList.AddRange(GetChildObjects<T>(child, name));//指定集合的元素添加到List队尾   
            }
            return childList;
        } 

调用:

List<Button> listButtons = GetChildObjects<Button>(parentPanel, "button1");

http://hi.baidu.com/nuuobvxckybfyzq/item/b3053ee7e2c23a0a560f1d99

 

posted on 2012-11-22 14:07  ﹎蓝言觅ぷ雨  阅读(1440)  评论(0编辑  收藏  举报