原文:
WPF查找子控件和父控件方法
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