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.