WPF 在子页面中获取父类窗体

  WPF 在子页面中获取父类窗体

/// <summary>
/// 子页面获取父类窗体
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="reference"></param>
/// <returns></returns>
public static T GetAncestor<T>(DependencyObject reference) where T : DependencyObject
{
    DependencyObject parent = VisualTreeHelper.GetParent(reference);
    while (!(parent is T) && parent != null)
    {
        parent = VisualTreeHelper.GetParent(parent);
    }
    if (parent != null)
        return (T)parent;
    else
        return null;
}

//在子页面中调用
GetAncestor<MainWindow>(this);

 

posted @ 2019-09-30 14:42  段小波  阅读(1704)  评论(0编辑  收藏  举报