简体   繁体   English

恢复的WPF窗口

[英]Restored WPF Window

I have an option to start my mainwindow minimized. 我可以选择最小化启动我的主窗口。 The window is set to SizeToContent="WidthAndHeight". 窗口设置为SizeToContent =“ WidthAndHeight”。 when I click to restore the window it opens larger than the initial WidthAndHeight. 当我单击以还原窗口时,它的打开大于初始WidthAndHeight。 I use the following in the MainWindow.xaml.cs 我在MainWindow.xaml.cs中使用以下内容

   private void WindowStart()
    {
        if (LocalSystem.StartMinimized)
        {
            WindowState = WindowState.Minimized;
            ShowInTaskbar = true;
        }
        if (LocalSystem.StartOnTop)
        {
            Topmost = true;
        }
        Activate();
    }

Consider keeping track of the state change of your WPF window. 考虑跟踪WPF窗口的状态变化。 Add an event handler of the StateChanged event of your Window and keep track of the Window width and height. 添加Window的StateChanged事件的事件处理程序,并跟踪Window的宽度和高度。

You could keep track of the size of the window like this: 您可以像这样跟踪窗口的大小:

public MainWindow() {

 InitializeComponent();
  _lastState = this.WindowState;
  _initialWidth = this.ActualWidth;
  _initialHeight = this.ActualHeight;
   this.StateChanged += Window_StateChanged;
}


    WindowState _lastState;
    double _initialwidth, _initialHeight;

    private void Window_StateChanged(object sender, EventArgs e)
    {
        if (this.WindowState != _lastState)
        {
          if (_lastState == WindowState.Minimized && this.WindowState == WindowState.Maximized){
            this.Width = _initialWidth;
            this.Height = _initialHeight;

           }
           _lastState = this.WindowState;

        }
    }

Note the use of ActualHeight and ActualWidth. 注意使用ActualHeight和ActualWidth。 The Window actual dimensions will be known after InitializeComponent is run inside its constructor. 在InitializeComponent的构造函数中运行后,将知道Window的实际尺寸。 A restored or unminized, as you so eloquently put it, window is window where the State goes from WindowState.Minimized to WindowState.Maximized. 正如您雄辩地说的那样,还原或未最小化的窗口是状态从WindowState.Minimized到WindowState.Maximized的窗口。

Note that we try to minimize the amount of code behind in WPF apps, as a best practice is to use MVVM. 请注意,由于最佳实践是使用MVVM,因此我们尝试将WPF应用程序中的代码量减至最少。 You could though consider creating a WPF behavior class for restoring initial size of Window, after all it is a generic behavior. 尽管您毕竟可以考虑创建WPF行为类来还原Window的初始大小,但这毕竟是一种常规行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM