Monthly Archives: February 2015

Building a WPF app using MVVM and Prism 5 – Part 1

A friend who is just getting into WPF recently asked me for advice on how best to create a WPF application that allows access to multiple data sources for read-only viewing purposes. Like many developers in our industry (investment banking), he was coming to WPF from a Winforms/VBA background and hadn’t yet fully grokked the usual WPF paradigms.

This series of blog posts will describe the standard Windows WPF application creation, using VS2013, Prism 5 and a pretty strict MVVM implementation.

Set the stage

Create a new solution with two projects, one standard C# class library project for common code and one WPF application project for UI code. I’ve named my common code assembly WpfDataDemo.Core, and left my UI assembly as WpfDataDemo.

Core assemblies

Nuget your code by downloading Prism and the Unity extensions and set them as references in both your Core and UI assemblies.

The minimum Nuget packages required

The minimum Nuget packages required

In your WPF application project, rename your MainWindow.xaml class to Shell.xaml and add a Bootstrapper.cs.

Bootstrapper

In the Bootstrapper.cs, inherit from UnityBootstrapper and override InitializeShell and CreateShell as below.


public class Bootstrapper : UnityBootstrapper
 {
    protected override void InitializeShell()
   {
      Application.Current.MainWindow = (Window) Shell;
      Application.Current.MainWindow.Show();
   }

   protected override DependencyObject CreateShell()
   {
      return ServiceLocator.Current.GetInstance<Shell>();
   }
 }

Set your project to start from the Bootstrapper by

  1. opening App.xaml and deleting the StartUri reference.
  2. opening App.xaml.cs, overriding OnStartup and initialising the Bootstrapper.

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;

namespace WpfDataDemo
{
 /// <summary>
 /// Interaction logic for App.xaml
 /// </summary>
 public partial class App : Application
 {
    protected override void OnStartup(StartupEventArgs e)
    {
       var bootstrapper = new Bootstrapper();
       bootstrapper.Run();
    }
 }
}

Delete StartupUri

Check that everything works by pressing F5 and ensuring that your Shell window pops up.