/// 获得指定元素的父元素 /// </summary> /// <typeparam name="T">指定页面元素</typeparam> /// <param name="obj"></param> /// <returns></returns> public T GetParentObject<T>(DependencyObject obj) where T : FrameworkElement { DependencyObject parent = VisualTreeHelper.GetParent(obj); while (parent != null) { if (parent is T) { return (T)parent; } parent = VisualTreeHelper.GetParent(parent); } return null; } /// <summary> /// 获得指定元素的所有子元素 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <returns></returns> public List<T> GetChildObjects<T>(DependencyObject obj) 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) { childList.Add((T)child); } childList.AddRange(GetChildObjects<T>(child)); } return childList; }
/// 查找子元素 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <param name="name"></param> /// <returns></returns> public T GetChildObject<T>(DependencyObject obj, string name) where T : FrameworkElement { DependencyObject child = null; T grandChild = null; 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))) { return (T)child; } else { grandChild = GetChildObject<T>(child, name); if (grandChild != null) return grandChild; } } return null; }
转载自http://blog.csdn.net/duanzi_peng/article/details/17094639