窗口位置动态“会话”

时间:2015-02-09 15:57:28

标签: c# wpf window position location

我有一个应用程序“弹出”一个带有ShowDialog的窗口。可以在应用程序生命周期中多次调用ShowDialog。

所以,我想知道是否可以(简单地)将Window位置默认设置为“CenterOwner”(就像现在一样)。但是,如果用户更改窗口的位置,则在主应用程序的生命周期中,下次将在上一个位置弹出窗口。 但是下次他将运行该应用程序时,该窗口将在CenterOwner中弹出。

没有大量代码可以吗?

感谢。希望我一直很清楚。

1 个答案:

答案 0 :(得分:1)

它不会占用很多代码。首先,在对话框的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;
    }
}