CJF
CJF

Reputation: 167

Is there a better way to position a secondary window's startup location relative to the main window?

I'm trying to open another window from a menu control located on my main window and I want this window's startup position to be centered relative to the main window. I have achieved this by setting the Owner property of the secondary window to my main window and setting the WindowStartupLocation property in XAML to CenterOwner, like this:

PopupWindow about = new PopupWindow();
about.Owner = Application.Current.MainWindow;
about.Show();
about.Owner = null;

The problem with this is that a window with an Owner seems to always stay on top of the Owner and whenever the Owner window is minimized, the Owned window also minimizes. To fix this I remove the Owner after the window is shown. The code seems to work fine, but it also feels a little bit like a hack.

I know there is a way to do this by setting the startup location to manual and then calculating where the window should be positioned, but I'm starting the secondary window from a popup control and I couldn't find a way to reference a window other than main. I think I could loop through the Windows collection and check a property to see if it's the window I need, but that almost seems worse than what I'm doing here.

Is there a better or more standard way of doing this?

Upvotes: 0

Views: 97

Answers (1)

Gaurav Mall
Gaurav Mall

Reputation: 2412

There is no "best" way per se to do this kind of thing. It actually doesn't have any built-in function. All of the methods for doing this are kind of "hacks", you might say. A standard way of doing this is getting the coordinates of the main window and based on the about window calculate where you want its location to be. Or you can do it your way too. Here is a simple example:

int width = mainwindow.getWidth() / 2;
int height = mainWindow.getHeight() / 2;
int locationWidth = width - about.getWidth() / 2;
int locationHeight = height - about.getHeight() / 2;

// Then set it
about.Location = new Cursor(locationWidth, locationHeight);

I don't remember exactly how to set the location, because I'm not on my normal computer. But you get the idea. Also, we do width - about.getWidth() / 2, because in C# the location is set not from the center but from the top left corner. Hope it helps.

Upvotes: 1

Related Questions