本文介绍了在Application_Startup方法创建WPF窗口是空白的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个WPF窗口在一个XAML文件的项目和相关的C#code隐藏文件。如果我设置的StartupUri = MainWindow.xaml在App.xaml中这个窗口打开的窗口中,当我开始我的应用程序如预期。

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.

不过,我想我的应用程序采取命令行参数,然后决定是否应该打开GUI与否。所以不是我设置启动= Application_Startup在我App.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.

    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.

推荐答案

添加 window.InitializeComponent()似乎这样的伎俩:

            MainWindow window = new MainWindow();
            Application.Current.MainWindow = window;
            window.InitializeComponent();
            window.Show();

我平时喜欢有为什么东西或不工作,一点解释。我在这种情况下,没有任何线索。我可以看到网上的例子不包括的InitializeComponent,但我产生完全相同的错误,因为你做的(事件,不检查参数)。

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).

这篇关于在Application_Startup方法创建WPF窗口是空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 10:25