Share via


Walking the Visual Tree in Avalon

Sometimes you just need to walk the tree of Visuals in Avalon.  It's easy to do, but it is even easier if you have a nice Visitor-pattern implementing tree walker.  So:

 

  using System;
   using System.Collections;
   using System.Diagnostics;
   using System.Windows;
   using System.Windows.Controls;
  using System.Windows.Media;
 using System.Windows.Media.Media3D;

 public delegate void VisualVisitor(Visual v, int depth);

    public class VisualTreeWalker
   {
       private Visual root;
        private int visualCount;

        public event VisualVisitor VisualVisited;

       public VisualTreeWalker(Visual root)
        {
           this.root = root;
       }

       public int Walk()
       {
           this.visualCount = 0;
           this.RecurseVisuals(this.root, 1);
          return this.visualCount;
        }

       private void RecurseVisuals(Visual visual, int currentDepth)
        {
           this.visualCount++;
         this.OnVisualVisit(visual, currentDepth);

           foreach (Visual child in VisualOperations.GetChildren(visual))
          {
               this.RecurseVisuals(child, currentDepth + 1);
           }
       }

       private void OnVisualVisit(Visual v, int currentDepth)
      {
           if (this.VisualVisited != null)
         {
               this.VisualVisited(v, currentDepth);
            }
       }
   }

Comments

  • Anonymous
    August 21, 2005

    Putting Constants in your XAML File? x:Static Is Your Friend.
    Building an Avalon application: Part...