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

namespace FLY.ControlLibrary
{
    public static class COMMON
    {
        public static Window GetWindow(DependencyObject dobj)
        {
            return GetParent<Window>(dobj);
            //DependencyObject dobj_window = dobj;
            ////一直向上找,直到找到window
            //do
            //{
            //    if (dobj_window is Window)
            //    {
            //        break;
            //    }
            //    dobj_window = System.Windows.Media.VisualTreeHelper.GetParent(dobj_window);
            //} while (dobj_window != null);
            //return dobj_window as Window;
        }

        public static T GetParent<T>(DependencyObject dobj) where T : DependencyObject
        {
            //一直向上找,直到找到window
            do
            {
                if (dobj is T)
                {
                    break;
                }
                dobj = System.Windows.Media.VisualTreeHelper.GetParent(dobj);
            } while (dobj != null);
            return (T)dobj;
        }
        /// <summary>
        /// 获取 DataContext
        /// </summary>
        /// <param name="dobj"></param>
        /// <returns></returns>
        public static object GetDataContext(DependencyObject dobj)
        {
            object dataContext = null;
            do
            {
                if (dobj is FrameworkElement)
                {
                    dataContext = (dobj as FrameworkElement).DataContext;
                    if (dataContext != null)
                    {
                        break;
                    }
                }
                dobj = System.Windows.Media.VisualTreeHelper.GetParent(dobj);
            } while (dobj != null);
            return dataContext;
        }
        public static T GetParent<T>(DependencyObject dobj, string name) where T : FrameworkElement
        {
            do
            {
                if ((dobj is T) && (((T)dobj).Name == name))
                {
                    break;
                }
                dobj = System.Windows.Media.VisualTreeHelper.GetParent(dobj);
            } while (dobj != null);
            return (T)dobj;
        }
    }
}