8

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.

enter image description here

Eric Anastas
  • 21,675
  • 38
  • 142
  • 236

2 Answers2

10

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

Daniel Gimenez
  • 18,530
  • 3
  • 50
  • 70
  • Isn't the InitializeComponent method called in the MainWindow constructor by default? – Avram Tudor Jul 03 '13 at 08:39
  • 3
    You've probably just removed `InitializeComponent` from the constructor of the `MainWindow` class. This is required to run the code in the designer generated code (the MainWindow.g.cs file you might have spotted) – Charleh Jul 03 '13 at 08:55
  • Ah ha! Yes I must have deleted InitializeComponent() from the constructor. Adding it back fixed the problem. Can anyone explain why it did work work when I used StartupUri? – Eric Anastas Jul 03 '13 at 18:06
0

I created a sample application, and removed the StartupUri and set the Startup to the method you provided. Everything seems to work as expected, the content of the window is displayed, so maybe, as Daniel mentioned, you're missing the call to InitializeComponent method in your MainWindow constructor.

Avram Tudor
  • 1,468
  • 12
  • 18