在WPF Visual Tree中查找父控件

实现

    private 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;
        }
        
        return FindVisualParent<T>(parentObject);
    }

使用

 var userControl = FindVisualParent<UserControl>(AssociatedObject);