Starting a WPF app programmatically (without a startup uri)

The default project template for WPF applications assumes that you want your main application class to be xaml-based. However, this is not a requirement and you can change it. Doing so allows you to write your own application entry point method and create your own application instance configured the way that you want.

So, you can delete your App.xaml and App.xaml.cs files and create an App.cs file in their place. In that file, do something like this:

internal class App : Application
    public static int Main(string[] args)
        App app = new App();
        // Setup your application as you want before running it
        return app.Run(new MainWindow());

    public App()
        // (Optional) Load your application resources file (which has a "Page" build action, not "ApplicationDefinition",
        // and a root node of type "ResourceDictionary", not "Application")
        Resources = (ResourceDictionary)Application.LoadComponent(new Uri("/MyAssemblyName;component/Resources.xaml", UriKind.Relative));

This allows you specify your main window whichever way you want before running the application. Your application resources file would look something like this:

    <!-- Put application resources here -->

I always structure my WPF applications this way because it seems simpler and provides more control over how the application is run. (I created a custom WPF application project template in Visual Studio.)

What's your thoughts on this?


Protected by WP Anti Spam