Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to customize startup of WPF application?

Tags:

wpf

startup

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"

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.

like image 740
Boris Avatar asked Nov 16 '12 22:11

Boris


People also ask

How do I change the startup window in WPF?

If you look at App. xaml class of your WPF application, you will see the following XAML code. Here the StartupUri sets the startup Window of an application. If you want to change the Startup window to some other window, just change this value.

How does a WPF application start?

Run method of Application class in WPF is used to starts an application. The code snippet in Listing 1 creates an Application instance and calls Run method. Run method can also take a Windows instance as a parameter and the passed instance Windows is the startup window.

How do I run a specific window in WPF?

Just delete the StartupUri="MainWindow. xaml" attribute in App. xaml , Add a Program class to your project containing a Main method, and then go to the project properties and set the startup object to YourAssemblyName.

Which XAML file specifies about application startup?

You can declaratively specify the main window and application-scope resources using XAML (StartupUri and Resources, respectively).


2 Answers

You can remove the StartupUri attribute from the App.xaml.

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

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

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.

like image 141
Eric Olsson Avatar answered Sep 21 '22 17:09

Eric Olsson


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

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

like image 22
mveith Avatar answered Sep 20 '22 17:09

mveith