如何编辑一个WPF应用程序的主窗口的构造函数? [英] 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.
不过,我不能从那里MainWindow的构造函数被调用搞清楚。另外我试图通过主窗口的成员函数来传递对象,但 app.MainWindow
是空
在 app.Run()
被调用。后 app.Run()
就是所谓的代码不返回,直到程序终止。
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.
另一个posibility会是存储对象的静态类,并有主窗口访问的,但是这似乎过于复杂。
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?
推荐答案
您可以不喜欢这样。
首先进入的App.xaml
键,删除此行的StartupUri =MainWindow.xaml
来防止WPF自动显示主窗口
。
First go into App.xaml
and remove this line StartupUri="MainWindow.xaml"
to prevent WPF from automatically showing the MainWindow
.
接下来右键点击的App.xaml
,然后选择查看代码
打开 App.xaml.cs
。在这个文件中,我们需要重写 OnStartup
事件。
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);
}
在 OnStartup
我们然后可以实例化主窗口
和表现出来。
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.
这篇关于如何编辑一个WPF应用程序的主窗口的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!