在 Application_Startup 方法中创建的 WPF 窗口是空白的
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17438659/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF Window created in Application_Startup method is blank
提问by Eric Anastas
I have a WPF window in a project with a XAML file and associated C# code behind file. If I set "StartupUri=MainWindow.xaml" in App.xaml to this window the window opens as expected when I start my application.
我在一个带有 XAML 文件和关联的 C# 代码隐藏文件的项目中有一个 WPF 窗口。如果我在 App.xaml 中将“StartupUri=MainWindow.xaml”设置为这个窗口,当我启动我的应用程序时,窗口会按预期打开。
However, I want my application to to take command line parameters and then decided if it should open the GUI or not. So instead I've set "Startup=Application_Startup" in my App.xaml file which is defined as shown below.
但是,我希望我的应用程序接受命令行参数,然后决定是否应该打开 GUI。因此,我在 App.xaml 文件中设置了“Startup=Application_Startup”,其定义如下所示。
private void Application_Startup(object sender, StartupEventArgs e)
{
if (e.Args.Length > 1)
{
//do automated tasks
}
else
{
//open ui
MainWindow window = new MainWindow();
this.MainWindow = window;
window.Show();
}
}
Yet when I run this the window displayed is totally blank.
然而,当我运行它时,显示的窗口完全是空白的。


回答by Daniel Gimenez
Adding window.InitializeComponent()seems to do the trick:
添加window.InitializeComponent()似乎可以解决问题:
MainWindow window = new MainWindow();
Application.Current.MainWindow = window;
window.InitializeComponent();
window.Show();
I usually like to have a little explanation on why something does or doesn't work. I have no clue in this case. I can see that the examples online don't include InitializeComponent, and yet I produce the same exact error as you do (event without checking for args).
我通常喜欢对为什么某些东西有效或无效的原因做一些解释。在这种情况下,我没有任何线索。我可以看到在线示例不包括 InitializeComponent,但我产生了与您相同的错误(事件不检查 args)。
回答by Avram Tudor
I created a sample application, and removed the StartupUri and set the Startup to the method you provided. Everything seems to work as expected, the content of the window is displayed, so maybe, as Daniel mentioned, you're missing the call to InitializeComponent method in your MainWindow constructor.
我创建了一个示例应用程序,并删除了 StartupUri 并将 Startup 设置为您提供的方法。一切似乎都按预期工作,显示了窗口的内容,所以也许正如 Daniel 提到的,您在 MainWindow 构造函数中缺少对 InitializeComponent 方法的调用。

