using System.Windows;
using System.Windows.Input;
using System;
using System.Windows.Media;
using System.Windows.Documents;

namespace RoutedEventsExample
{
    public partial class MainWindow : Window
    {
        Run run1;
        Run run2;
        public MainWindow()
        {
            InitializeComponent();
            run1 = new Run();
            run1.Foreground = new SolidColorBrush(Colors.Red);
            run1.FontSize = 10;
            run1.FontWeight = FontWeights.Bold;
            run2 = new Run();
            run2.Foreground = new SolidColorBrush(Colors.Green);
            run2.FontSize = 10;
            run2.FontWeight = FontWeights.Bold;
        }

        private void RoutedEventExample_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {            
            textBlock.Text = "";
            GetVisualTree(this, 0,e );
        }
        void GetVisualTree(DependencyObject obj, int level, MouseButtonEventArgs e)
        {
            //określona liczba miejsc od lewej strony
            string space = new string(' ', level);
          
            
            //wypisanie danych obiektu do konsoli
            Console.WriteLine(String.Format("{0}{1}) {2}", space, level, obj.GetType().Name));
            if(obj.Equals(e.OriginalSource)||obj.Equals(e.Source))
            {
                if (obj.Equals(e.OriginalSource)) {
                    run1.Text = String.Format("{0}{1}) {2} [OriginalSource]\n", space, level, obj.GetType().Name);
                    textBlock.Inlines.Add(run1);
                }
                else if (obj.Equals(e.Source)) {
                    run2.Text = String.Format("{0}{1}) {2} [Source]\n", space, level, obj.GetType().Name);
                    textBlock.Inlines.Add(run2);
                }
            }
            else
            {
                textBlock.Inlines.Add(String.Format("{0}{1}) {2}\n", space, level, obj.GetType().Name));
            }
            //pętla rekurencyjnie wywołujące metodę GetVisualTree dla kolejnych elementów - dzieci
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
                GetVisualTree(VisualTreeHelper.GetChild(obj, i), level+1, e);
        }
    }
}
