假如想获取一个Grid(名称为grid1)上所有的Button按钮,则代码如下:
List<Button> collection = GetChildObjects<Button>(grid1, "");//第2个参数为空,表示查找所有指定类型的控件(返回一个Button集合)
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, ""));//指定集合的元素添加到List队尾 } return childList; }
原文地址:http://blog.csdn.net/pandeveloper/article/details/6749408