Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
594 views
in Technique[技术] by (71.8m points)

c# - How do I edit the MainWindow constructor of a WPF application?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could do it like this.

First go into App.xaml and remove this line StartupUri="MainWindow.xaml" to prevent WPF from automatically showing the MainWindow.

Next right click on App.xaml and choose View Code to open up App.xaml.cs. Inside this file we need to to override the OnStartup event.

protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);
}

Inside OnStartup we can then instantiate our MainWindow and show it.

protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);

    MainWindow mw = new MainWindow();
    mw.Show();
}

And now we can use this to load an alternative Constructor that we can use to pass on more information.

App.xaml.cs

protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);

    MainWindow mw = new MainWindow(5);
    mw.Show();
}

MainWindow.xaml.cs

public MainWindow()
{
    InitializeComponent();
}

public MainWindow(int number) : base()
{

}

I prefer to chain my constructors, but it's of course not a requirement by any means.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...