[英]How to customize startup of WPF application?
When a new WPF Application project is created, MainWindow.xaml
, App.xaml
and their corresponding code behind classes are automatically generated.创建新的 WPF Application 项目时,会自动生成
MainWindow.xaml
、 App.xaml
及其对应的代码隐藏类。 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"
在
App.xaml
中有一个属性定义了最初要运行的 window,默认情况下它是StartupUri="MainWindow.xaml"
I have created a new Dispatcher
class in the same project.我在同一项目中创建了一个新的
Dispatcher
class。 At startup, I want the instance of that class Dispatcher
to be constructed and then one of its method to run.在启动时,我希望构建 class
Dispatcher
的实例,然后运行其方法之一。 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?该方法实际上会创建并显示
MainWindow
window。那么我该如何修改App.xaml
或App.xaml.cs
以实现它呢? Or, if it cannot be done by App
, how should I implement it?或者,如果
App
无法完成,我应该如何实现? Thanks.谢谢。
You can remove the StartupUri
attribute from the App.xaml. 您可以从App.xaml中删除
StartupUri
属性。
Then, by creating an override for OnStartup()
in the App.xaml.cs, you can create your new instance of your Dispatcher
class. 然后,通过在App.xaml.cs中为
OnStartup()
创建覆盖,您可以创建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 workaround for a bug if you use this method to customize app startup and suddenly none of the Application-level resources can be found. 如果您使用此方法自定义应用程序启动,并且突然找不到任何应用程序级资源,我最近发现了此错误的解决方法。
1.In App.xaml, To replace the StartupUri with a subscription to the Startup event. 1.在App.xaml中,将StartupUri替换为对Startup事件的订阅。
For instance,例如,
Startup="Application_Startup" in.xaml. Startup="Application_Startup" in.xaml。
public partial class App : Application
{
private void Application_Startup(object sender, StartupEventArgs e)
{
// Create the startup window
MainWindow wnd = new MainWindow();
// Do stuff here, e.g. to the window
wnd.Title = "Something else";
// Show the window
wnd.Show();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.