操作說明:取得與設定主應用程式視窗
此範例展示該如何取得與設定主應用程式視窗。
範例
在 Windows Presentation Foundation (WPF) 應用程式中實例化的第一個Window會被Application自動設定為主應用程式視窗。 要實例化的第一個Window很可能是指定為啟動統一資源標識碼 (URI) 的視窗(請參閱StartupUri)。
第一個Window也可以使用程式代碼實例化。 其中一個範例是在應用程式啟動期間開啟視窗,如下所示:
public partial class App : Application
{
void App_Startup(object sender, StartupEventArgs e)
{
MainWindow window = new MainWindow();
window.Show();
}
}
Partial Public Class App
Inherits Application
Private Sub App_Startup(ByVal sender As Object, ByVal e As StartupEventArgs)
Dim window As New MainWindow()
window.Show()
End Sub
End Class
有時候,第一個實例化Window實際上不是主應用程式視窗,例如啟動顯示畫面。 在此情況下,您可以使用標記指定主應用程式視窗,如下所示:
<Application
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="StartupWindow.xaml"
>
<Application.MainWindow>
<NavigationWindow Source="MainPage.xaml" Visibility="Visible"></NavigationWindow>
</Application.MainWindow>
</Application>
無論是自動還是手動指定主視窗,您可以使用下列程式代碼從MainWindow取得主視窗,如下所示:
// Get the main window
Window mainWindow = this.MainWindow;
' Get the main window
Dim mainWindow As Window = Me.MainWindow