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
How to customize startup of WPF application?
提问by Boris
When a new WPF Application project is created, MainWindow.xaml
, App.xaml
and their corresponding code behind classes are automatically generated. In the App.xaml
there is an attribute that defines which window is going to be run initially and by the default it's StartupUri="MainWindow.xaml"
当创建一个新的WPF应用程序项目MainWindow.xaml
,App.xaml
及其对应的隐藏类代码自动生成。在App.xaml
有一个属性是哪个窗口将会定义了最初运行并默认它是StartupUri="MainWindow.xaml"
I have created a new Dispatcher
class in the same project. At startup, I want the instance of that class Dispatcher
to be constructed and then one of its method to run. That method would actually create and show the MainWindow
window. So how do I modify the App.xaml
or App.xaml.cs
in order to make it happen? Or, if it cannot be done by App
, how should I implement it? Thanks.
我Dispatcher
在同一个项目中创建了一个新类。在启动时,我希望Dispatcher
构造该类的实例,然后运行其方法之一。该方法实际上会创建并显示MainWindow
窗口。那么我如何修改App.xaml
orApp.xaml.cs
以使其发生?或者,如果它不能由 完成App
,我应该如何实现它?谢谢。
回答by Eric Olsson
You can remove the StartupUri
attribute 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 Dispatcher
class.
然后,通过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.
如果您使用此方法自定义应用程序启动并且突然找不到任何应用程序级资源,我最近发现了此解决方法的错误。