WPF window created in Application_Startup method is empty

I have a WPF window in a project with a XAML file and the associated C # code behind the file. If I set "StartupUri = MainWindow.xaml" in App.xaml to this window, the window opens as expected when I launch the application.

However, I want my application to accept command line options, and then decide whether it should open the graphical interface or not. So instead, I set "Startup = Application_Startup" to 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(); } } 

However, when I run this, the displayed window is completely empty.

enter image description here

+7
c # wpf
source share
2 answers

Adding window.InitializeComponent() seems like a trick:

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

I usually like to explain a little why something works or doesn't work. In this case, I have no idea. I see that the online examples do not include InitializeComponent, and yet I am throwing the exact same error as you (an event without checking for args).

+9
source share

I created a sample application and uninstalled StartupUri and installed Startup on the method you provided. Everything seems to work as expected, the contents of the window are displayed, so perhaps, as Daniel said, you are missing the call to the InitializeComponent method in the MainWindow constructor.

0
source share

All Articles