How to: Get and Set the Main Application Window

This example shows how to get and set the main application window.

Example

The first Window that is instantiated within a Windows Presentation Foundation (WPF) application is automatically set by Application as the main application window. The first Window to be instantiated will most likely be the window that is specified as the startup uniform resource identifier (URI) (see StartupUri).

The first Window could also be instantiated using code. One example is opening a window during application startup, like the following:

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

Sometimes, the first instantiated Window is not actually the main application window e.g. a splash screen. In this case, you can specify the main application window using markup, like the following:

<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>

Whether the main window is specified automatically or manually, you can get the main window from MainWindow using the following code, like the following:

// Get the main window
Window mainWindow = this.MainWindow;
' Get the main window
Dim mainWindow As Window = Me.MainWindow