我有一个用ShowDialog"弹出"窗口的应用程序。ShowDialog在应用程序生命周期中可以调用多次。
因此,我想知道是否可以(简单地)将Window位置默认设置为"CenterOwner"(就像现在一样)。但是,如果用户更改了窗口的位置,在主应用程序的生命周期中,下次它将在以前的位置弹出。但下次他运行应用程序时,CenterOwner中将弹出窗口。
在没有大量代码的情况下有可能吗
谢谢。希望我已经说清楚了。
它不需要太多代码。首先,在对话框的XAML中,您应该将启动位置设置为CenterOwner:
<Window WindowStartupLocation="CenterOwner"
Loaded="Window_Loaded"
>
接下来,在后面的代码中,您应该记住原始的开始位置,并保存窗口的位置(如果窗口关闭时已移动):
private double _startLeft;
private double _startTop;
static double? _forceLeft = null;
static double? _forceTop = null;
void Window_Loaded(object sender, RoutedEventArgs e)
{
// Remember startup location
_startLeft = this.Left;
_startTop = this.Top;
}
// Window is closing. Save location if window has moved.
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
if (this.Left != _startLeft ||
this.Top != _startTop)
{
_forceLeft = this.Left;
_forceTop = this.Top;
}
}
// Restore saved location if it exists
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
if (_forceLeft.HasValue)
{
this.WindowStartupLocation = System.Windows.WindowStartupLocation.Manual;
this.Left = _forceLeft.Value;
this.Top = _forceTop.Value;
}
}