My mainWindow needs to subscribe to some events from an object. The object is initialized before the MainWindow is created. I would like to pass this object to the mainWindow via its constructor.
However I can't figure out from where the MainWindow constructor is called. Alternatively I tried to pass the object via a member function of the MainWindow, but the app.MainWindow
is null
before app.Run()
is called. After app.Run()
is called the code doesn't return until the program terminates.
Another posibility would be storing the object in a static class and have the MainWindow access that, but this seems unnecessarily complicated.
I realize I can just create the object in the MainWindow constructor, but that would mean having to put a lot of other code there as well, pretty much the entire Main function.
How can I pass this object to my MainWindow? Or is the MainWindow constructor intended to function as the 'Main' for the entire program?
You could set the object as the DataContext of the MainWindow by declaring it in the XAML itself. (If you are trying to create a ViewModel, for instance). Other than that, WPF will create the instance in a way you can't control. You could put your own code in the App class to create and display the window, and remove the StartupUri from App.xaml.
You could do it like this.
First go into
App.xaml
and remove this lineStartupUri="MainWindow.xaml"
to prevent WPF from automatically showing theMainWindow
.Next right click on
App.xaml
and chooseView Code
to open upApp.xaml.cs
. Inside this file we need to to override theOnStartup
event.Inside
OnStartup
we can then instantiate ourMainWindow
and show it.And now we can use this to load an alternative
Constructor
that we can use to pass on more information.App.xaml.cs
MainWindow.xaml.cs
I prefer to chain my constructors, but it's of course not a requirement by any means.