WPF:如何设置对话框位置显示在应用程序的中心?
问题描述:
如何设置来自 .ShowDialog();
的对话框的位置显示在mainWindows的中心。
How to set Dialog's position that came from .ShowDialog();
to show at the center of the mainWindows.
这是我尝试设置位置的方式。
This is the way I try to set position.
private void Window_Loaded(object sender, RoutedEventArgs e)
{
PresentationSource source = PresentationSource.FromVisual(this);
if (source != null)
{
Left = ??
Top = ??
}
}
答
你可以尝试在Loaded事件中保持MainWindow,如下所示
You can try to get a hold of the MainWindow in the Loaded event like this
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Application curApp = Application.Current;
Window mainWindow = curApp.MainWindow;
this.Left = mainWindow.Left + (mainWindow.Width - this.ActualWidth) / 2;
this.Top = mainWindow.Top + (mainWindow.Height - this.ActualHeight) / 2;
}