WPF MVVM如何在 View 更改后重新居中应用程序窗口?

标签 wpf mvvm centering

我正在使用 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/

相关文章:

WPF BitmapImage 宽度/高度始终为 1?

WPF slider 自动工具提示在悬停时可见

wpf - 窗口 GotFocus 事件未触发

wpf - 用 View 模型替换列表中的对象

c# - 仅绑定(bind) ObservableCollection<T> 中的特定对象

css - margin: 0 auto 不会出现在中心

html - 图像不会与元素中心对齐

c# - 如何在wpf中的特定位置初始化新文本框

mvvm - 从 ViewModel 到 View 通信

html - 我怎样才能使这个提交按钮居中?