using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Diagnostics;


namespace LogicalVisualTreeSample {
  public partial class Window1 : System.Windows.Window {

    public Window1() {
      InitializeComponent();

      // Can dump the logical tree any time after InitComp
      Debug.WriteLine("Logical tree:");
      DumpLogicalTree(rootPanel, 0);
    }

    protected override void OnContentRendered(EventArgs e) {
      base.OnContentRendered(e);

      // Need to wait for layout before visual tree is ready
      Debug.WriteLine("Visual tree:");
      DumpVisualTree(rootPanel, 0);
    }

    void DumpLogicalTree(object parent, int level) {
      string typeName = parent.GetType().Name;
      string name = null;
      DependencyObject doParent = parent as DependencyObject;

      // Not everything in the logical tree is a dependency object
      if( doParent != null ) {
        name = (string)(doParent.GetValue(FrameworkElement.NameProperty) ?? "");
      }
      else {
        name = parent.ToString();
      }

      Debug.Write("                ".Substring(0, level * 2));
      Debug.WriteLine(string.Format("{0}: {1}", typeName, name));
      if( doParent == null ) { return; }

      foreach( object child in LogicalTreeHelper.GetChildren(doParent) ) {
        DumpLogicalTree(child, level + 1);
      }
    }

    void DumpVisualTree(DependencyObject parent, int level) {
      string typeName = parent.GetType().Name;
      string name = (string)(parent.GetValue(FrameworkElement.NameProperty) ?? "");
      Debug.Write("                ".Substring(0, level * 2));
      Debug.WriteLine(string.Format("{0}: {1}", typeName, name));

      for( int i = 0; i != VisualTreeHelper.GetChildrenCount(parent); ++i ) {
        DependencyObject child = VisualTreeHelper.GetChild(parent, i);
        DumpVisualTree(child, level + 1);
      }
    }

  }
}