Tales from the Smart Client

John Gossman's observations on Avalon development

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);
			}
		}
	}
Published Thursday, August 04, 2005 9:20 PM by JohnGossman

Comments

 

Life, Universe and Everything according to Dirk said:


Putting Constants in your XAML File? x:Static Is Your Friend.
Building an Avalon application: Part...
August 22, 2005 6:30 AM
New Comments to this post are disabled

© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Microsoft
Page view tracker