Floc
Floc

Reputation: 698

Window location dynamic on "session"

I've an application that "popup" a window with a ShowDialog. The ShowDialog can be called many times in the app life cycle.

So, I wonder if that possible (simply) to set the Window location to "CenterOwner" by default (like now). But if the user change the position of the window, in the life cycle of the main app, next time it will popup at the previous location. But next time he will run the app, the window will popup in the CenterOwner.

Is it possible without a lot of code behind ?

Thanks. Hope I've been clear.

Upvotes: 0

Views: 97

Answers (1)

RogerN
RogerN

Reputation: 3821

It doesn't take much code-behind. First, in your dialog's XAML you should be setting the startup location to CenterOwner:

<Window WindowStartupLocation="CenterOwner"
        Loaded="Window_Loaded"
        >

Next, in your code behind you should remember the original start location and save the window's location if it has been moved when the window closes:

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;
    }
}

Upvotes: 1

Related Questions