我正在使用 native WPF 和 MVVM 开发一个非常简单的应用程序。主要的“shell” View 使用我认为是一种常见的基本模式,其中它包含一个 ContentControl,它是数据绑定(bind)到事件 View 模型的,它通过数据模板注入(inject) View 。这是它的缩写版本:
<Window.DataContext>
<local:ShellViewModel/>
</Window.DataContext>
<Window.Resources>
<DataTemplate DataType="{x:Type local:DbConfigViewModel}">
<local:DbConfigView/>
</DataTemplate>
<DataTemplate DataType="{x:Type local:AuthenticationViewModel}">
<local:AuthenticationView/>
</DataTemplate>
</Window.Resources>
<DockPanel>
<ContentControl Content="{Binding CurrentViewModel}"/>
</DockPanel>
此窗口设置为根据 View 自动调整大小,并设置为居中启动。这适用于初始 View 。不过,有些 View 要大得多,当它们变得活跃时,它就会成为一个 UI 问题。我需要做的是让应用程序在 View 更改时重新居中。
到目前为止,我尝试的是对主窗口的 Left 和 Top 属性进行数据绑定(bind),如下所示:
<Window (....)
Width="auto" Height="auto"
SizeToContent="WidthAndHeight"
WindowStartupLocation="CenterScreen"
Left="{Binding WindowLeft}"
Top="{Binding WindowTop}">
我的导航与主 Windows View 模型中的一个方法相关联,因此在该方法中,将新 View 模型设置为 CurrentViewModel 属性后,我将调用此方法:
private void CenterWindow()
{
Rect workArea = System.Windows.SystemParameters.WorkArea;
WindowLeft = (workArea.Width - Application.Current.MainWindow.Width) / 2 + workArea.Left;
WindowTop = (workArea.Height - Application.Current.MainWindow.Height) / 2 + workArea.Top;
}
这似乎应该可以工作,但似乎正在发生的是 MainWindow.Width 和 Height 尚未调整,因此它基于上一个 View 而不是我刚刚实例化的 View 居中。
那么是否有一些事件或其他地方可以调用此代码,以便在呈现新 View 后发生?这甚至是正确的方法吗?
最佳答案
您需要在窗口中订阅 SizeChanged 然后:
private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
{
if (e.PreviousSize == e.NewSize)
return;
var w = SystemParameters.PrimaryScreenWidth;
var h = SystemParameters.PrimaryScreenHeight;
this.Left = (w - e.NewSize.Width) / 2;
this.Top = (h - e.NewSize.Height) / 2;
}
如果您希望在 viewModel 中使用交互事件,您可以使用它
关于WPF MVVM如何在 View 更改后重新居中应用程序窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21990866/