wpf 如何自定义WPF应用程序的启动?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13425425/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 23:34:23  来源:igfitidea点击:

How to customize startup of WPF application?

wpfstartup

提问by Boris

When a new WPF Application project is created, MainWindow.xaml, App.xamland their corresponding code behind classes are automatically generated. In the App.xamlthere is an attribute that defines which window is going to be run initially and by the default it's StartupUri="MainWindow.xaml"

当创建一个新的WPF应用程序项目MainWindow.xamlApp.xaml及其对应的隐藏类代码自动生成。在App.xaml有一个属性是哪个窗口将会定义了最初运行并默认它是StartupUri="MainWindow.xaml"

I have created a new Dispatcherclass in the same project. At startup, I want the instance of that class Dispatcherto be constructed and then one of its method to run. That method would actually create and show the MainWindowwindow. So how do I modify the App.xamlor App.xaml.csin order to make it happen? Or, if it cannot be done by App, how should I implement it? Thanks.

Dispatcher在同一个项目中创建了一个新类。在启动时,我希望Dispatcher构造该类的实例,然后运行其方法之一。该方法实际上会创建并显示MainWindow窗口。那么我如何修改App.xamlorApp.xaml.cs以使其发生?或者,如果它不能由 完成App,我应该如何实现它?谢谢。

回答by Eric Olsson

You can remove the StartupUriattribute from the App.xaml.

您可以StartupUri从 App.xaml 中删除该属性。

Then, by creating an override for OnStartup()in the App.xaml.cs, you can create your new instance of your Dispatcherclass.

然后,通过OnStartup()在 App.xaml.cs 中创建覆盖,您可以创建您的Dispatcher类的新实例。

Here's what my quick app.xaml.cs implementation looks like:

这是我的快速 app.xaml.cs 实现的样子:

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
      base.OnStartup(e);

      new MyClassIWantToInstantiate();
    }
  }
}

Update

更新

I recently discovered this workaroundfor a bug if you use this method to customize app startup and suddenly none of the Application-level resources can be found.

如果您使用此方法自定义应用程序启动并且突然找不到任何应用程序级资源,我最近发现了此解决方法的错误。

回答by mveith

Try to use the Startup event (class Application) - MSDN.

尝试使用启动事件(类应用程序)- MSDN

You can show MainWindow in this event handler - after you create a Dispatcher instance.

您可以在此事件处理程序中显示 MainWindow - 在创建 Dispatcher 实例之后。