using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;

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

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
        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;
        }
    }
}