[英]Centering new window in mainwindow
這可能是重復的,但我用Google搜索了它,並通過StackOverFlow查看以嘗試找到針對此問題的修復程序,但仍然無法正常工作。 我試圖在我的主窗口中居中放置一個窗口(輸入對話框)。 它應該垂直居中,並且新窗口(對話框)的寬度必須是MainWindow的寬度。
這是我到目前為止嘗試過的:
Application curApp = Application.Current;
Window mainWindows = curApp.MainWindow;
this.Left = mainWindows.Left;
this.Top = mainWindows.Top + (mainWindows.ActualHeight - this.ActualHeight) / 2;
this.Width = mainWindows.ActualWidth;
上面的代碼位於“對話框”窗口的已加載事件中。
盡管這使它垂直居中,但它並未將其放置在mainWindow的確切中心(即,Left屬性不匹配。)
請幫忙。
這就是我稱呼對話框的方式:
var dialog = new MyDialog();
dialog.ShowMessage("Capture Amount", "Please enter the 'Capture Amount'");
if (dialog.ShowDialog() == true) {
DialogResponse = dialog.ResponseAmount.ToString();
CustomTitleMain = "Main Window: " + CurrencyCode.ToString() + " " + DialogResponse.ToString();
}
DialogResponse,CurrencyCode和ResponseAmount是屬性。 前兩個是字符串,最后一個是十進制。
使用System.Windows.WindowStartupLocation.CenterOwner
並設置對話框窗口的Owner
屬性。
Window subWindow = new MyWindow();
subWindow.Owner = Application.Current.MainWindow;
subWindow.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
subwindow.ShowDialog();
您可以在Init中設置對話框的StartupLocation,如下所示:
Application curApp = Application.Current;
Window mainWindows = curApp.MainWindow;
this.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
this.Owner = mainWindows;
this.Left = mainWindows.Left;
this.Top = mainWindows.Top + (mainWindows.ActualHeight - this.ActualHeight) / 2;
this.Width = mainWindows.ActualWidth;
或在調用時進行設置:
var dialog = new MyDialog();
dialog.Owner = Application.Current.MainWindow;
dialog.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
dialog.ShowMessage("Capture Amount", "Please enter the 'Capture Amount'");
if (dialog.ShowDialog() == true) {
DialogResponse = dialog.ResponseAmount.ToString();
CustomTitleMain = "Main Window: " + CurrencyCode.ToString() + " " + DialogResponse.ToString();
}
但是請記住,您還可以通過xaml設置所有這些參數。 我認為這使它更具可讀性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.