Get and Set the Main Window of a WPF Application

If you look at App.xaml class of your WPF application, you will see the following XAML code.

<Application x:Class="WindowSample.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        
    </Application.Resources>
</Application>

Here the StartupUri sets the startup Window of an application. If you want to change the Startup window to some other window, just change this value.

Let's say you have a Window in your application called "MainArea.xaml". Just change the following red color code.

<Application x:Class="WindowSample.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainArea.xaml">
    <Application.Resources>
        
    </Application.Resources>
</Application>


If you want to do the same at run-time, you can do that as well. First, remove StartupUri from the above code. Then Startup event of Application and write the code below.

public partial class App : Application
{
void App_Startup(object sender, StartupEventArgs e)
{
MainArea window = new MainArea();
window.Show();
}
}