好this问题和this问题相似,但没有有效的答案。实际上,我希望WindowStartupLocation = CenterOwner可以工作……不行。它似乎将新窗口居中在网格列的中心,而不是主窗口的中心。所以我假设它认为是父母。其次,当我关闭对话框并再次打开它时,它没有居中,而是从上一个位置向右下移动。而且,如果我将主窗口移至第二个监视器,则弹出窗口仍将在默认监视器上打开。这些属性是错误的还是我只是认为它应该以不同的方式工作。我想我可以手动计算Top和Left属性。我只希望弹出窗口位于主窗口的中心,无论它在哪里。
可能是因为您没有设置所有者:
this.Owner = App.MainWindow; // for example
这就是我的方法,它始终使窗口始终居中。
为了扩展Will Eddins的评论,您可以在Window中为ShowDialog()或Show()创建一个重载方法:
public void ShowDialog(Window owner)
{
this.Owner = owner;
this.ShowDialog();
}
public void Show(Window owner)
{
this.Owner = owner;
this.Show();
}
或重载构造函数:
public MyWindow(Window owner)
: this()
{
this.Owner = owner;
}
如果为此创建扩展,则可以重复使用这个好主意:
/// <summary>
/// Opens a window modally, with an owner
/// </summary>
/// <param name="window">The window to open</param>
/// <param name="opener">The owner of the window getting opened</param>
/// <returns>window.ShowDialog()</returns>
public static bool? ShowDialog(this Window window, Window opener)
{
window.Owner = opener;
return window.ShowDialog();
}
我有同样的问题...但是主要是因为,当我想摆脱子窗口时,我使用hide()
而不是close()
...因此,当您重新打开它时,因为它是隐藏的并且没有关闭,所以当父窗口移动时,它仍在其启动位置打开...
所以关闭子窗口而不是例如在完成使用后将其隐藏。
可能导致此问题的其他原因是在调用DataContext
之后设置InitializeComponent()
。
如果您有这样的代码隐藏:
public CustomWindow(CustomViewModel viewModel)
{
InitializeComponent();
DataContext = viewModel;
}
将其更改为:
public CustomWindow(CustomViewModel viewModel)
{
DataContext = viewModel;
InitializeComponent();
}