#45 – Two Ways to Create WPF Controls

When working with WPF, you can always create controls in one of two basic ways:

  • Create the control programmatically, from within your code (e.g. C#)
  • Create the control declaratively, in XAML

As an example, here are two different ways to create a main window for a WPF application.

To create a main window in code, you would add code the the Application object’s event handler for the Startup event.  You would typically create the window object and then call its Show method.

private void Application_Startup(object sender, StartupEventArgs e)
    MainWindow win = new MainWindow();

More typically, you’d specify the application’s main window in XAML by specifying a value for the application’s StartupUri attribute.  For the default project created by the New Project wizard, you’d do this in App.xaml:

<Application x:Class="WpfApplication.App"