WPF Window created in Application_Startup method is blank

.net, c#, wpf

Solution

Adding `window.InitializeComponent()` seems to do the trick:

            MainWindow window = new MainWindow();
            Application.Current.MainWindow = window;
            window.InitializeComponent();
            window.Show();

I usually like to have a little explanation on why something does or doesn't work. I have no clue in this case. I can see that the examples online don't include InitializeComponent, and yet I produce the same exact error as you do (event without checking for args).

Problem

I have a WPF window in a project with a XAML file and associated C# code behind file. If I set "StartupUri=MainWindow.xaml" in App.xaml to this window the window opens as expected when I start my application. However, I want my application to to take command line parameters and then decided if it should open the GUI or not. So instead I've set "Startup=Application_Startup" in my App.xaml file which is defined as shown below. ``` private void Application_Startup(object sender, StartupEventArgs e) { if (e.Args.Length > 1) { //do automated tasks } else { //open ui MainWindow window = new MainWindow(); this.MainWindow = window; window.Show(); } } ``` Yet when I run this the window displayed is totally blank.

Original source

Related problems