Creating a WPF Application Using Prism

Introduction

This article shows how to create a Windows application in WPF using the Prism Library. The solution includes recommended practices and techniques and is the basis for the procedures in Prism. The sample was created in Visual Studio 2012, it can also be developed in Visual Studio 2008 and 2010, because WPF supports the .Net framework 3.5 to the latest version. To create a solution with the Prism Library, the following must be done.

  1. Create a solution with a shell project: In this task, you create the initial Visual Studio solution and add a WPF Application project that is the basis of solutions built using the Prism Library. This project is known as the shell project.
     
  2. Setup the shell: In this task, you set up a window, the shell window, to host various User Interface (UI) components in a decoupled manner.
     
  3. Setup the application's bootstrapper: In this task, you set up the code that initializes the application.
     
  4. AddModule: In this task, you will create a module and add it to your solution. A module in Prism is a logical unit in your application. Adding a module to your solution involves the following tasks:
     
  5. AddView
     
  6. Add a region to the shell: The task describes how to add an ItemsControl control to the shell window and associate a region to it. In a subsequent task, you will dynamically add a view to this region.

1. Create a solution with a shell project

  1. Use Visual Studio to create a new WPF application. To do this, point to "New" on the File menu, and then click "Project".
     
  2. In the Project types list, select "Windows" in the Visual C# node. In the Templates box, click WPF Application. Finally, set the project's name to "simpleprismapplication" then specify a valid location, then click "OK".
     
  3. Using Windows Explorer, create a folder named PrismLibrary inside your solution's folder, and then copy the following assemblies into it (they are located in the "Source\bin\PrismLibraryfolder"):
     
    • Microsoft.Practices.Prism.dll. This assembly contains the implementation of the Prism Library core components, such as modularity, logging services, communication services, and definitions for several core interfaces. It also contains the implementation of the Prism Library components that target WPFapplications, including commands, regions, and events.
     
    • Microsoft.Practices.Prism.UnityExtensions.dll. This assembly contains the base and utility classes you can reuse in applications built with the Prism Library that consumes the Unity Application Block. For example, it contains a bootstrapper base class, the UnityBootstrapper class, that creates and configures a Unity container with the default Prism Library services when the application starts.
     
    • Microsoft.Practices.Unity.dll. This assembly enables you to use the Unity Application Block in your application. By default, applications built using Prism use the Unity ApplicationBlock or MEF. However, developers who prefer to use various container implementations can build adapters for them using the provided extensibility points in the Prism Library.
     
    • Microsoft.Practices.ServiceLocation.dll. This assemblycontains the Common Service Locator interface used by Prism to provide an abstraction over Inversion of Control containers ands ervice locators; therefore, you can change the container implementation with ease.
     
  4. In the "simpleprismapplication" project, add references to the assemblies listed in the preceding step.
     
  5. The shell window is the top-level window of an application based on the Prism Library. This window is a place to host various UI components that expose a way for itself to be dynamically populated by others, and it may also contain common UI elements, such as menus and toolbars. The shell window sets the overall appearance of the application.

2. Set up the shell

  1. In Solution Explorer, rename the file MainWindow.xaml to Shell.xaml.
     
  2. Open the code-behind file Shell.xaml.cs and rename the MainWindow class to "Shell". If the preview changes then the Rename dialog box appears,click "Apply".
     
  3. Main Window renaming using Visual Studio refactoring tools
     
  4. In XAML view, open the Shell.xaml file, and then set the following attribute values to the window's root element:

    x:Class= "simpleprismapplication.Shell" (this matches the codebehind class's name)

    Title= "Simple Prism Application"

    Your code should look like the following.
    1. <Windowx:ClassWindowx:Class="simpleprismapplication.Shell"  
    2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
    3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
    4. Title="Simple Prism Application" Height="300"Width="300">  
    5.   <Grid>  
    6.   </Grid>  
    7. </Window> 
  5. In the Shell.xaml file, add the following namespace definition to the root Window element. You need this namespace to use an attached property for regions that are defined in the Prism Library.

    xmlns:prism="http://www.codeplex.com/prism"
     
  6. Replace the Grid control in the shell window with an ItemsControl control named MainRegion, as shown in the following code.
    1. <Window x:Class="simpleprismapplication.Shell"  
    2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
    3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
    4. xmlns:prsm="http://www.codeplex.com/prism"  
    5. Title="Simple Prism Application" Height="350" Width="525">  
    6. </Window>
  7. In the ItemsControl control definition, set the attached property prism:RegionManager.RegionName to "MainRegion", as shown in the following code. This attached property indicates that a region named MainRegion is associated with the control.
    1. <ItemsControl Name="MainRegion" prsm:RegionManager.RegionName="MainRegion" >  
    2. </ItemsControl>
  8. When the shell window is instantiated, WPF resolves the value of the prism:RegionManager.RegionName attached property and invokes a callback in the Region Manager class. This callback creates a region and associates it with the ItemsControl control.

3. Set up the application's bootstrapper

  1. Add a new class file named Bootstrapper.cs to the "simpleprismapplication" project.
     
  2. Add the following using statements at the top of the file. You will use them to refer to elements referenced in the UnityBootstrapper class.
    1. using System.Windows;  
    2. using Microsoft.Practices.Prism.Modularity;  
    3. using Microsoft.Practices.Prism.UnityExtensions;  
    4. using Microsoft.Practices.Unity;  
  3. Update the Bootstrapper class's signature to inherit from the UnityBootstrapper class.

    1. class Bootstrapper : UnityBootstrapper  
    2. {  
    3. }

     

  4. Override the Create Shell method in the Bootstrapper class. In this method, create an instance of the shell window and return it, as shown in the following code.

    1. protected override DependencyObject CreateShell()  
    2. {  
    3.     return new Shell();  
    4. }

     

  5. You can turn the shell object to have the UnityBootstrapper base class attach an instance of the region manager service to it. The regionmanager service is a service included in the Prism Library that manages regions in the application. By having a region manager instance attached to the shell window, you can declaratively register regions from XAML code that will exist in the scope of the shell window and child views.
     

  6. Override the InitializeShell method in the Bootstrapper class. In this method, display the shell to the user.

    1. protected override void InitializeShell()  
    2. {  
    3.     base.InitializeShell();  
    4.     App.Current.MainWindow = (Window)this.Shell;  
    5.     App.Current.MainWindow.Show();  
    6. }

     

  7. Override the ConfigureModuleCatalog method. In this template method, you populate the module catalog with modules. The module catalog interface is "Microsoft.Practices.Prism.Modularity.IModuleCatalog" and it contains metadata for all the modules in the application. Because the application contains no modules at this point, the implementation of the ConfigureModuleCatalog method should simply call the base implementation and return. You can paste the following code in your Bootstrapper class to implement the method.

    1. protected override void ConfigureModuleCatalog()  
    2. {  
    3.     base.ConfigureModuleCatalog();  
    4. } 

     

  8. Open the file App.xaml.cs and initialize the Bootstrapper in the handler for the Startup event of the application, as shown in the following code. By doing this, the bootstrapper code will we executed when the application starts.

    1. public partial class App : Application  
    2. {  
    3.    protected override void OnStartup(StartupEventArgs e)  
    4.     {  
    5.        base.OnStartup(e);  
    6.         Bootstrapper bootstrapper = new Bootstrapper();  
    7.         bootstrapper.Run();  
    8.     }  
    9. } 

     

  9. Open the App.xaml file and remove the attribute StartupUri. Because you're manually instantiating the shell window in your bootstrapper, this attribute is not required. The code in the App.xaml file should look like the following.

    1. <Applicationx:ClassApplicationx:Class="simpleprismapplication.App"  
    2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
    3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">  
    4.   <Application.Resources>  
    5.   </Application.Resources>  
    6. </Application> 

     

  10. Build and run the application. You should see an empty Simple Prism Application window, as shown in the following illustration.

4. Adding Module to Project

  1. Add a new class library project to your solution. To do this, right-click the simple Prism application solution node in Solution Explorer, point to Add, and then click "New Project". In the Project types list, select "Windows" in the Visual C# node. In the Templates box, click "Class Library". Finally, set the project's name to simple Prism applicationModule, and then click "OK". The following illustration shows your solution. Solution with a module named simpleprismapplicationmodule.

    Model.png
     
  2. Add references to your module to the following WPF assemblies. To do that, right-click the "simpleprismapplicationmodule" project in Solution Explorer and then click "Add Reference". In the Add Reference dialog box, click the .NET tab, click the following assemblies and then click "OK":

    • PresentationCore.dll

    • PresentationFramework.dll

    • WindowsBase.dll

    • System.Xaml.dll
     
  3. Add references in your module to the Microsoft.Practices.Prism.dll Prism Library assemblies. To do this, right-click the HelloWorldModule project in Solution Explorer, and then click "AddReference". In the Add Reference dialog box, click the Browse tab, click the following assemblies, and then click "OK":
     
  4. Rename the Class1.cs file to "simpleprismapplicationmodule.cs". Open the file "simpleprismapplicationmodule.cs" and impliment the Microsoft.Practices.Prism.Modularity namespace in the class.
     
  5. Implement the IModuleinterface in the simpleprismapplicationmodule class and create the constructure of this class.
     
  6. Add a Views folder having name View to store the views of your application to the simple Prism application module project. Again add one more folder and rename it to "ViewModel" to store the view models.

    Note: The folders mentioned above can be created in the simple Prism application project also, but it is a good practice to create a separate module to manage the code.
     
  7. In your shell project, add a reference to the simple Prism application module project. Open theBootstrapper.cs file and explore the ConfigureModuleCatalog method. The method implementation is shown in the following code.

    1. protected override void ConfigureModuleCatalog()  
    2. {  
    3.    base.ConfigureModuleCatalog();  
    4. } 

     

  8. Update theConfigureModuleCatalog method to register the "simpleprismapplicationmodule" module with the module catalog instance. To do this, you can add the following codes in theConfigureModuleCatalog below the
    "base.ConfigureModuleCatalog();" code.

    ModuleCatalog moduleCatalog= (ModuleCatalog)this.ModuleCatalog;

    moduleCatalog.AddModule (typeof (simpleprismapplication.simpleprismapplicationmodule));
     
  9. Now add the module and register the module application with the shell. That is done in the next steps in the adding of the view to the application.

5. Adding a View

Add a new WPF user control to your module by right-clicking the Views folder in Solution Explorer, point to "Add" and then click "New Item". In the Add New Item dialog box, select the User Control (WPF) template, set the name to simple Prism application view.xaml and then click "Add". Add a text block to the view and set the text to "Hello Friends" and save the file.

  1. <usercontrol x:class="simpleprismapplicationmodule.View.simpleprismapplicationview"  
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
  3.     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  
  4.     mc:ignorable="d" d:designheight="300" d:designwidth="300">  
  5. <Grid>  
  6. <TextBlock Text="Hellow Friends" Foreground="Green" HorizontalAlignment="Center" VerticalAlignment="Center"FontFamily="Calibri" FontSize="24" FontWeight="Bold"></TextBlock>  
  7. </Grid>  
  8. </usercontrol> 

6. Add a region to the shell

  1. Open the "simpleprismapplicationmodule.cs" file. Add the followingusing statement to the top of the file. You will use it to refer to the region elements in the Prism Library.

    1. using Microsoft.Practices.Prism.Regions;

     

  2. Create a private read-only instance variable to hold a reference to the region manager and paste the following code inside the class body.

    1. using Microsoft.Practices.Prism.Regions;

     

  3. Add the constructor of the "simpleprismapplicationmodule" class to obtain a region manager instance through the constructor dependency injection and store it in the regionManager instance variable. The constructor has to take a parameter of type "Microsoft.Practices.Prism.Regions.IRegionManager". You can paste the following code inside the class body to implement the constructor.

    1. public simpleprismapplicationmodule(IRegionManager regionManager)  
    2. {  
    3.    this.regionManager = regionManager;  
    4. }

     

  4. In the Initialize method, invoke the RegisterViewWithRegion method on the RegionManager instance. This method registers a region name with its associated view type in the region view registry; the registry is responsible for registering and retrieving these mappings.The RegisterViewWithRegion method has two overloads. When you want to register a view directly, you use the first overload that requires two parameters, the region name and the type of the view.

    1. public void Initialize()  
    2. {  
    3.     regionManager.RegisterViewWithRegion("MainRegion",typeof(View.simpleprismapplicationview));  
    4. }

     

  5. The UI composition approach used in the preceding code is known as view discovery. When using this approach, you specify the views and the region where the views will be loaded. When a region is created, it asks for its associated views and automatically loads them.

    Note:

    The region's name must match the name defined in the RegionName attribute of the region.

    Output

    appwindow.bmp

Summary

In this explanation we have seen how to create a new application in WPF using Prism library.