Start a WPF Application Through Code

By Michael Detras

Using the default WPF application project template creates App.xaml and App.xaml.cs classes used for starting the application. The StartupUri is set to the MainWindow via XAML. We can also do this through code.

Delete the App.xaml and App.xaml.cs files and create another class which will contain the Main method entry point. Here's an example.

namespace
WpfApplication1
{
    public class App
    {
         [STAThread]
        static void Main()
        {
             var application = new Application();
            var mainWindow = new MainWindow();
            application.Run(mainWindow);
        }
     }
}

Alternatively, you can do it like this, which uses the MainWindow property of the Application.

namespace WpfApplication1
{
    public class App
    {
         [STAThread]
        static void Main()
        {
             var application = new Application();            
            application.MainWindow = new MainWindow();
            application.MainWindow.Show();
            application.Run();
        }
     }
}


Start a WPF Application Through Code  (1984 Views)