WPF 中有时候会使用 Frame + Page 的方式来实现页面切换的效果,但往往我们都需要在Page中对主窗体进行一些调整.
那么首先我们需要获得主窗体对象.有下面两种方式
1.简单方式
var window = Window.GetWindow(this);
if (window != null) {
window.MinWidth = 300;
window.MinHeight = 300;
}
2.复杂方式.遍历树
//此方法也可以声明成静态方法
public 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;
}
//调用 :
var window = GetAncestor<Window>(this);
if (window != null) {
window.Width = 300;
window.Height = 300;
}
需要注意的是.需要在 Page_Loaded 之后调用,否则 window == null