DoubleVoid
DoubleVoid

Reputation: 795

Can't find resource Locator when creating window in App.xaml

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?!

Upvotes: 0

Views: 1081

Answers (1)

wingerse
wingerse

Reputation: 3796

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.

Upvotes: 2

Related Questions