0

I am creating my main window inside the App.xaml.cs constructor like this:

MainWindow wnd = new MainWindow();

Application.Current.MainWindow = wnd;
wnd.Show();

Starting the application gives me a XamlParseException, the resource with the name "Locator" cannot be found.

This is the suspicious line:

<DockPanel x:Name="MainPanel"  DataContext="{Binding MainWindowViewModel, Source={StaticResource Locator}}" LastChildFill="True">

Using StartupUri in App.xaml works just fine.

What am I doing wrong?!

Nate Barbettini
  • 51,256
  • 26
  • 134
  • 147
DoubleVoid
  • 777
  • 1
  • 16
  • 46

1 Answers1

2

I presume you have your Locator resource in the App.xaml. The reason why it does not work when you put your code in the constructor is because App.xaml is not loaded yet. If you see the default Main method generated by visual studio, you can see that App.InitializeComponent is called after the constructor. The resources in the xaml file are initialized at this point.

You can fix the issue by putting your code in the Application.Startup event which Occurs when the Run method of the Application object is called. (If StartupUri is set, it's also initialized after Run is called.)

protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);
    var window = new MainWindow();
    window.Show();
}

Of course you can subscribe to that event and write the code in an event hander. However, when we want to subscribe to events in a base class, it's better to override the OnXXX method for the corresponding event.

On and btw, you don't need this line Application.Current.MainWindow = wnd;. It will be done automatically for you by wpf.

wingerse
  • 3,670
  • 1
  • 29
  • 61
  • Thank you very much, works like a charm. What If I don't want the GUI to show up at all?! Creating no window does not really help, since the app is still running without a window. I want to implement a /noGui parameter, if it's set, no window will be created and some task get's done. Calling Application.Current.Shutdown() seems to be wrong to me. – DoubleVoid Apr 21 '16 at 06:29
  • In that case, you need to modify App.g.cs. There you can find the Main method. You can add your logic here. If the parameter is set, don't run the app. Else do. – wingerse Apr 21 '16 at 07:01
  • Application.Current.Shutdown() will not work because it makes App.Run() return which means the program will end if you don't have custom logic set at Main – wingerse Apr 21 '16 at 07:03
  • Application.Current.Shutdown() seems to work, the program closes. And the App.g.cs is inside the obj folder. I guess this is a more correct approach, when altering the App.g.cs: http://stackoverflow.com/questions/1052868/wpf-shut-off-autogen-of-main-in-app-g-cs . Guess I will stick to Shutdown() for now, seems to be working well. Start => Check console param => do stuff => Shutdown() – DoubleVoid Apr 22 '16 at 09:54