WPF应用打开以后,经常会改动尺寸和窗体的最大化状态等。
从用户体验来说,应用最好把这些尺寸的变化保存下来。
1、在使用的设置里面添加MainWindowState和MainWindowBounds两个配置:
2、窗体添加两个事件:
SizeChanged="Window_SizeChanged" StateChanged="Window_StateChanged"
3、添加后台代码:
/// <summary> /// 窗体大小改变 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Window_SizeChanged(object sender, SizeChangedEventArgs e) { if (this.WindowState == WindowState.Normal) { mSettings.MainWindowBounds = this.RestoreBounds; mSettings.Save(); } } /// <summary> /// 窗体状态变化 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Window_StateChanged(object sender, EventArgs e) { if (this.WindowState != WindowState.Minimized) { mSettings.MainWindowState = this.WindowState; mSettings.Save(); } }
4、窗体初始化的时候调用:
var bounds = mSettings.MainWindowBounds; this.WindowStartupLocation = WindowStartupLocation.CenterScreen; this.Width = bounds.Width; this.Height = bounds.Height; this.WindowState = mSettings.MainWindowState;