(Version: Avalon CTP 2004 November)
What does mainWindow‘s visual tree look like when a simple Xaml file (below) is rendered onto the screen?
<Window x:Class="AvalonApplication1.Window1" xmlns="http://schemas.microsoft.com/2003/xaml" xmlns:x="Definition" Text="AvalonApplication1" ID="mainWindow">
<Grid>
<Button Content="Click Me" Click="ButtonClick"/>
</Grid>
</Window>
Well, it depends on the style definition for Window, Grid and Button controls. With the default Windows XP theme, the following printout shows the VisualTree structure for mainWindow.
AvalonApplication1.Window1
System.Windows.Controls.Border
System.Windows.Controls.Grid
System.Windows.Documents.AdornerDecorator
System.Windows.Controls.ContentPresenter
System.Windows.Controls.Grid
System.Windows.Controls.Button
System.Windows.Controls.Grid
System.Windows.Shapes.Rectangle
System.Windows.Shapes.Rectangle
System.Windows.Shapes.Rectangle
System.Windows.Shapes.Rectangle
System.Windows.Shapes.Rectangle
System.Windows.Shapes.Rectangle
System.Windows.Shapes.Rectangle
System.Windows.Shapes.Rectangle
System.Windows.Controls.Border
System.Windows.Controls.FlowPanel
System.Windows.Controls.ContentPresenter
System.Windows.Controls.Text
System.Windows.Controls.Grid + GridLinesRenderer
System.Windows.Controls.Grid + GridLinesRenderer
System.Windows.Documents.AdornerLayer
System.Windows.Controls.Primitives.StatusBar
System.Windows.Controls.Primitives.ResizeGrip
System.Windows.Controls.Grid+GridLinesRenderer
The following code is used to generate the information.
public static class Utility
{
public static string GetVisualTreeInfo(Visual element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
StringBuilder sb1 = new StringBuilder();
VisualCollection vc = VisualOperations.GetChildren(element);
if (vc.Count == 0)
{
sb1.Append("[No Visual Child] - ");
sb1.Append(element.GetType());
}
else
{
sb1.Append(element.GetType());
sb1.Append(Environment.NewLine);
WriteToVisualTreeInfo(sb1, vc, 1);
}
return sb1.ToString();
}
private static void WriteToVisualTreeInfo(StringBuilder sb, VisualCollection vc, int level)
{
const int indent = 4;
foreach (Visual v in vc)
{
sb.Append(new string(' ', level * indent));
sb.Append(v.GetType());
sb.Append(Environment.NewLine);
VisualCollection vcollection = VisualOperations.GetChildren(v);
if (vcollection.Count > 0)
{
WriteToVisualTreeInfo(sb, vcollection, level + 1);
}
}
}
}
I end this post with a question for my reader: what does MessageBox display when the Button is clicked and its event handler is this?
private void ButtonClick(object sender, RoutedEventArgs e)
{
Button newButton = new Button();
MessageBox.Show(Utility.GetVisualTreeInfo(newButton));
}
(This posting is provided "AS IS" with no warranties, and confers no rights. Use of included script samples are subject to the terms specified at http://www.microsoft.com/info/cpyright.htm)