I'm trying to implement storing and restoring main window state and size in my WPF application. My current code looks like following:
MainWindowViewModel.cs (ran on main window's
OnLoaded
):public void NotifyLoaded() { var uiConfig = configurationService.Configuration.UI; if (uiConfig.MainWindowSizeSet.Value) access.SetWindowSize(new System.Windows.Size(uiConfig.MainWindowWidth.Value, uiConfig.MainWindowHeight.Value)); if (uiConfig.MainWindowLocationSet.Value) access.SetWindowLocation(new System.Windows.Point(uiConfig.MainWindowX.Value, uiConfig.MainWindowY.Value)); if (uiConfig.MainWindowMaximized.Value) access.SetWindowMaximized(true); }
The
access
is anIMainWindowAccess
, implemented by theMainWindow
itself (this is my way of providing communication between viewmodel and window, while still keeping logic and view separated). Methods are being implemented in the following way:void IMainWindowAccess.SetWindowSize(Size size) { this.Width = size.Width; this.Height = size.Height; } void IMainWindowAccess.SetWindowLocation(Point point) { this.Left = point.X; this.Top = point.Y; } void IMainWindowAccess.SetWindowMaximized(bool maximized) { this.WindowState = maximized ? WindowState.Maximized : WindowState.Normal; }
I'm storing window position and size on window closing, but only if window is not maximized. I do that to avoid situation when user tries to restore window and it restores to its maximized size.
public void NotifyClosingWindow() { var windowSize = access.GetWindowSize(); var windowLocation = access.GetWindowLocation(); var maximized = access.GetMaximized(); configurationService.Configuration.UI.MainWindowMaximized.Value = maximized; if (!maximized) { Models.Configuration.UI.UIConfig uiConfig = configurationService.Configuration.UI; uiConfig.MainWindowWidth.Value = windowSize.Width; uiConfig.MainWindowHeight.Value = windowSize.Height; uiConfig.MainWindowSizeSet.Value = true; uiConfig.MainWindowX.Value = windowLocation.X; uiConfig.MainWindowY.Value = windowLocation.Y; uiConfig.MainWindowLocationSet.Value = true; } configurationService.Save(); }
The problem is that though I restore size and location of the window before maximizing it (so it should restore to its former size), it still restores to maximized size (effectively clicking the restore button changes button to maximize - size and location remains the same).
How should I set size and location of the window and then maximize it, so that size and location will be properly stored?
Window.StateChanged
event? – Pavel Anikhouski