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);