WPF查找指定类型的父/子控件

public static T FindVisualChild<T>(DependencyObject obj) where T : DependencyObject
{
    if (obj != null)
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(obj, i);
            if (child != null && child is T)
            {
                return (T)child;
            }
            T childItem = FindVisualChild<T>(child);
            if (childItem != null) return childItem;
        }
    }
    return null;
}

public static T FindVisualParent<T>(DependencyObject child) where T : DependencyObject
{
    DependencyObject parentObject = VisualTreeHelper.GetParent(child);
    if (parentObject == null) return null;
    T parent = parentObject as T;
    if (parent != null)
    {
        return parent;
    }
    else
    {
        return FindVisualParent<T>(parentObject);
    }
}

  

posted @ 2020-08-02 10:42  梦醒江南·Infinite  阅读(419)  评论(0编辑  收藏  举报