WPF WindowStartupLocation="CenterOwner" not really center, and pops all over, why?

Viewed 35827

Well this question and this question are similar but no answers that work. In fact I was hoping WindowStartupLocation=CenterOwner would work...it doesn't. It seems to center the new window in the center of a grid column, not the center of the main window. So I'm assuming it thinks that is the parent. Second when I close the dialog and open it again it is not centered but moved down and right from the previous position. And if I move the main window to a second monitor the popup still opens on the default monitor. Are these properties wrong or am I just thinking it should work in a different way. I suppose I could calculate the Top and Left properties manually. I just want the popup to be centered in the main window no matter where it is.

5 Answers

In addition, we can use:

this.Owner = App.Current.MainWindow;

Or Application instead of App.
And place it in a child window constructor:

    public partial class ChildWindow : Window
    {
        public ChildWindow()
        {
            InitializeComponent();

            DataContext = new ChildWindowViewModel();

            this.Owner = App.Current.MainWindow;
        }
    }

Something else that can cause this is setting DataContext after InitializeComponent() is called.

If you have code-behind like this:

    public CustomWindow(CustomViewModel viewModel)
    {
        InitializeComponent();
        DataContext = viewModel;
    }

Change it to:

    public CustomWindow(CustomViewModel viewModel)
    {
        DataContext = viewModel;
        InitializeComponent();
    }
Related