| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- using System.Windows;
- using System.Windows.Media;
- namespace Muchinfo.PC.Common.Helpers
- {
- public class WPFVisualTreeHelper
- {
- /// <summary>
- /// 从父容器中查找指定类型的控件
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="parent"></param>
- /// <returns></returns>
- public static T FindVisualChild<T>(DependencyObject parent) where T : DependencyObject
- {
- if (parent == null) return null;
- for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
- {
- var childObject = VisualTreeHelper.GetChild(parent, i);
- if (childObject == null) return null;
- var child = childObject as T;
- if (child == null)
- {
- var childItem = FindVisualChild<T>(childObject);
- if (childItem != null) return childItem;
- }
- return child;
- }
- return null;
- }
- /// <summary>
- /// 查找指定类型的父容器
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="child">The child.</param>
- /// <returns>``0.</returns>
- public static T FindVisualParent<T>(DependencyObject child) where T : DependencyObject
- {
- if (child == null) return null;
- var parentObject = VisualTreeHelper.GetParent(child);
- if (parentObject == null) return null;
- var parent = parentObject as T;
- return parent ?? FindVisualParent<T>(parentObject);
- }
- ///// <summary>
- ///// Finds the child.
- ///// </summary>
- ///// <typeparam name="T"></typeparam>
- ///// <param name="node">The node.</param>
- ///// <returns>``0.</returns>
- //public static T FindChild<T>(DependencyObject node)
- // where T : DependencyObject
- //{
- // if (node == null) return null;
- // T found = null;
- // var childlen = VisualTreeHelper.GetChildrenCount(node);
- // for (int i = 0; i < childlen; i++)
- // {
- // var child = VisualTreeHelper.GetChild(node, i);
- // var target = child as T;
- // if (target == null)
- // {
- // found = FindChild<T>(child);
- // if (found != null)
- // break;
- // }
- // else
- // {
- // found = (T)child;
- // break;
- // }
- // }
- // return found;
- //}
- }
- }
|