Counting all the Visuals in an Avalon tree


Here’s an example of using the VisualTreeWalker from the last post:

	public class TreeStatistics
{
private int visualCount;
private int greatestVisualDepth;
private int depthTotal;
private FrameworkElement root;

public TreeStatistics(FrameworkElement root)
{
this.root = root;
}

public void GetStatistics()
{
this.visualCount = 0;
this.greatestVisualDepth = 0;
this.depthTotal = 0;

VisualTreeWalker walker = new VisualTreeWalker(this.root);
walker.VisualVisited += this.StatisticsVisitor;
walker.Walk();
walker.VisualVisited -= this.StatisticsVisitor;
}

private void StatisticsVisitor(Visual v, int currentDepth)
{
this.depthTotal += currentDepth;
this.visualCount++;
if (currentDepth > this.greatestVisualDepth)
{
this.greatestVisualDepth = currentDepth;
}
}

public int VisualCount
{
get { return this.visualCount; }
}

public int GreatestVisualDepth
{
get { return this.greatestVisualDepth; }
}

public double AverageVisualDepth
{
get { return (double)this.depthTotal / (double)this.visualCount; }
}
}


Comments (1)

  1. Putting Constants in your XAML File? x:Static Is Your Friend.

    Building an Avalon application: Part…