WPFVisualTreeHelper.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using System.Windows;
  2. using System.Windows.Media;
  3. namespace Muchinfo.PC.Common.Helpers
  4. {
  5. public class WPFVisualTreeHelper
  6. {
  7. /// <summary>
  8. /// 从父容器中查找指定类型的控件
  9. /// </summary>
  10. /// <typeparam name="T"></typeparam>
  11. /// <param name="parent"></param>
  12. /// <returns></returns>
  13. public static T FindVisualChild<T>(DependencyObject parent) where T : DependencyObject
  14. {
  15. if (parent == null) return null;
  16. for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
  17. {
  18. var childObject = VisualTreeHelper.GetChild(parent, i);
  19. if (childObject == null) return null;
  20. var child = childObject as T;
  21. if (child == null)
  22. {
  23. var childItem = FindVisualChild<T>(childObject);
  24. if (childItem != null) return childItem;
  25. }
  26. return child;
  27. }
  28. return null;
  29. }
  30. /// <summary>
  31. /// 查找指定类型的父容器
  32. /// </summary>
  33. /// <typeparam name="T"></typeparam>
  34. /// <param name="child">The child.</param>
  35. /// <returns>``0.</returns>
  36. public static T FindVisualParent<T>(DependencyObject child) where T : DependencyObject
  37. {
  38. if (child == null) return null;
  39. var parentObject = VisualTreeHelper.GetParent(child);
  40. if (parentObject == null) return null;
  41. var parent = parentObject as T;
  42. return parent ?? FindVisualParent<T>(parentObject);
  43. }
  44. ///// <summary>
  45. ///// Finds the child.
  46. ///// </summary>
  47. ///// <typeparam name="T"></typeparam>
  48. ///// <param name="node">The node.</param>
  49. ///// <returns>``0.</returns>
  50. //public static T FindChild<T>(DependencyObject node)
  51. // where T : DependencyObject
  52. //{
  53. // if (node == null) return null;
  54. // T found = null;
  55. // var childlen = VisualTreeHelper.GetChildrenCount(node);
  56. // for (int i = 0; i < childlen; i++)
  57. // {
  58. // var child = VisualTreeHelper.GetChild(node, i);
  59. // var target = child as T;
  60. // if (target == null)
  61. // {
  62. // found = FindChild<T>(child);
  63. // if (found != null)
  64. // break;
  65. // }
  66. // else
  67. // {
  68. // found = (T)child;
  69. // break;
  70. // }
  71. // }
  72. // return found;
  73. //}
  74. }
  75. }