WPF中查找指定类型的父控件

时间:2021-10-23 08:24:31
     /// <summary>
/// 查找父控件
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="child"></param>
/// <returns></returns>
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);
}
}