I need to store my app window’s size/position and state when the user closes the app and set them back when the user thereafter opens the app.
I did this easily using registry keys (is this even the best way to do?), but I’m wondering where I actually should put the code to set those properties.
I need to set them when the window first “appears” I think. But I have several methods that could be used in this case, namely:
- Window.Show()
- Window.Activate()
- Window.ApplyTemplate()
- Window.Arrange()
- Window.ArrangeCore()
- Window.ArrangeOverride()
- Window.BeginInit()
- Window.EndInit()
- Window.Measure()
- Window.MeasureCore()
- Window.MeasureOverride()
- Window.OnApplyTemplate()
- Window.OnInitialized()
- Window.OnRender()
- Window.UpdateLayout()
I’m aware that most of them just are a bad idea (UpdateLayout() will be called waaaaaaay too often for instance). Idealy I’m looking for a method that will only be called once in the window’s life so that I don’t have to add a flag checking if this is the method’s first call.
so which one would be the best in this case? and why?
side question: I put the code to save the values in Window.Close() (I’m overriding the method in my MyWindow class), But I could as well have put it in Window.OnClosing() or Window.OnClosed(). Does this make any difference in my case?
side question (bis): I also have to save a datagrid’s column order, where should I put both “saving” and “loading” code in this case?
My Choice: I finally ended up putting the code to load the values from the registry in window.Show().
the reason I did this is because of 2 things:
I store the state of the window, (minimized/maximized) and the way WPF does it, I need to first set the width/height, then the maximized state (if needed), otherwise it messes up the layout. And if I don’t set the width/height first, I loose them when I de-maximize the window thereafter. So I have to do things in this order precisely: Width + height and them state. (Also, this is necessary when working with multiple screens, otherwise you loose the screen you were working on). This means that some of the methods above are impractical (the “measure” ones for instance)
adding to this, if I put my code in most of the methods above-mentioned, I’ll get a bad looking effect on first display: the window will first appear with its height and width set, in the middle of the screen, and then after a small delay, the window gets maximized.
putting the code in window.Show() managed to solve those 2 issues. I might have had the same result with one or more of the other methods, but I simply got fed-up with trying different configurations and ended up using the first one that gave me entire satisfaction.