Show the Visual Tree of a Control

By Michael Detras

Sometimes, we might need to look at the visual tree of a control to know what comprises it. One scenario that we would need to traverse the tree is to set a property of a control in the visual tree.

Here is a sample code to traverse the visual tree of a DataGrid and display it on the output window in Visual Studio.

public partial class MainWindow : Window
{
    public MainWindow()
    {
         InitializeComponent();
    }

     private void DataGrid_Loaded(object sender, RoutedEventArgs e)
    {
        TraverseOutputVisualTree(sender as DependencyObject);
    }

     public static void TraverseOutputVisualTree(DependencyObject d, int depth = 0)
    {
         var count = VisualTreeHelper.GetChildrenCount(d);
        for (int i = 0; i < count; i++)
        {
            var child = VisualTreeHelper.GetChild(d, i);
           Debug.WriteLine(new string('\t', depth) + child.GetType());

            TraverseOutputVisualTree(child, depth + 1);
        }
    }
}    

The output of the preceding code is shown below. I added some tabs to indicate the depth of the controls in the visual tree.

System.Windows.Controls.Border
System.Windows.Controls.ScrollViewer
System.Windows.Controls.Grid
System.Windows.Controls.Button
System.Windows.Controls.Grid
System.Windows.Shapes.Rectangle
System.Windows.Shapes.Polygon
System.Windows.Controls.Primitives.DataGridColumnHeadersPresenter
System.Windows.Controls.Grid
System.Windows.Controls.Primitives.DataGridColumnHeader
System.Windows.Controls.Grid
Microsoft.Windows.Themes.DataGridHeaderBorder
System.Windows.Controls.ContentPresenter
System.Windows.Controls.Primitives.Thumb
System.Windows.Controls.Border
System.Windows.Controls.Primitives.Thumb
System.Windows.Controls.Border
System.Windows.Controls.ItemsPresenter
System.Windows.Controls.DataGridCellsPanel
System.Windows.Controls.ScrollContentPresenter
System.Windows.Controls.ItemsPresenter
System.Windows.Controls.Primitives.DataGridRowsPresenter
System.Windows.Documents.AdornerLayer
System.Windows.Controls.Primitives.ScrollBar
System.Windows.Controls.Grid
System.Windows.Controls.Primitives.ScrollBar

Show the Visual Tree of a Control  (1159 Views)