VisualTreeExtensions.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // (c) Copyright Microsoft Corporation.
  2. // This source is subject to the Microsoft Public License (Ms-PL).
  3. // Please see http://go.microsoft.com/fwlink/?LinkID=131993] for details.
  4. // All other rights reserved.
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Diagnostics;
  8. using System.Globalization;
  9. using System.Linq;
  10. using System.Windows;
  11. using System.Windows.Media;
  12. namespace System.Windows.Controls
  13. {
  14. /// <summary>
  15. /// A static class providing methods for working with the visual tree.
  16. /// </summary>
  17. internal static class VisualTreeExtensions
  18. {
  19. /// <summary>
  20. /// Retrieves all the visual children of a framework element.
  21. /// </summary>
  22. /// <param name="parent">The parent framework element.</param>
  23. /// <returns>The visual children of the framework element.</returns>
  24. internal static IEnumerable<DependencyObject> GetVisualChildren(this DependencyObject parent)
  25. {
  26. Debug.Assert(parent != null, "The parent cannot be null.");
  27. int childCount = VisualTreeHelper.GetChildrenCount(parent);
  28. for (int counter = 0; counter < childCount; counter++)
  29. {
  30. yield return VisualTreeHelper.GetChild(parent, counter);
  31. }
  32. }
  33. /// <summary>
  34. /// Retrieves all the logical children of a framework element using a
  35. /// breadth-first search. A visual element is assumed to be a logical
  36. /// child of another visual element if they are in the same namescope.
  37. /// For performance reasons this method manually manages the queue
  38. /// instead of using recursion.
  39. /// </summary>
  40. /// <param name="parent">The parent framework element.</param>
  41. /// <returns>The logical children of the framework element.</returns>
  42. internal static IEnumerable<FrameworkElement> GetLogicalChildrenBreadthFirst(this FrameworkElement parent)
  43. {
  44. Debug.Assert(parent != null, "The parent cannot be null.");
  45. Queue<FrameworkElement> queue =
  46. new Queue<FrameworkElement>(parent.GetVisualChildren().OfType<FrameworkElement>());
  47. while (queue.Count > 0)
  48. {
  49. FrameworkElement element = queue.Dequeue();
  50. yield return element;
  51. foreach (FrameworkElement visualChild in element.GetVisualChildren().OfType<FrameworkElement>())
  52. {
  53. queue.Enqueue(visualChild);
  54. }
  55. }
  56. }
  57. }
  58. }