using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Media;

namespace TextWrappingGridView
{
    public static class DependencyObjectExtensions
    {
        public static TParent GetVisualParent<TParent>(this DependencyObject dependencyObject) where TParent : DependencyObject
        {
            return dependencyObject.GetVisualParent<TParent>(false);
        }

        public static TParent GetVisualParent<TParent>(this DependencyObject dependencyObject, bool includeSelf) where TParent : DependencyObject
        {
            if (includeSelf && dependencyObject is TParent)
            {
                return dependencyObject as TParent;
            }
            return dependencyObject.GetVisualParent<TParent, TParent>();
        }

        public static TParent GetVisualParent<TParent, TRestriction>(this DependencyObject dependencyObject) where TParent : DependencyObject
        {
            DependencyObject parent = null;

            if (dependencyObject != null)
                parent = VisualTreeHelper.GetParent(dependencyObject);

            while ((parent != null) && !(parent is TParent && parent is TRestriction))
            {
                parent = VisualTreeHelper.GetParent(parent);
            }

            return (TParent)parent;
        }
    }
}