简体   繁体   English

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

[英]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.xamlApp.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.xamlApp.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. 如果您使用此方法自定义应用程序启动,并且突然找不到任何应用程序级资源,我最近发现了错误的解决方法。

Try to use the Startup event (class Application) - MSDN . 尝试使用Startup事件(类Application) - MSDN

You can show MainWindow in this event handler - after you create a Dispatcher instance. 您可以在创建Dispatcher实例后在此事件处理程序中显示MainWindow。

1.In App.xaml, To replace the StartupUri with a subscription to the Startup event. 1.在App.xaml中,将StartupUri替换为对Startup事件的订阅。

  1. Use the event in App.xaml.cs.使用 App.xaml.cs 中的事件。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM