microsoft prism wpf application

14
Prism 4.1 Developer Guide – For Beginners Microsoft Prism 4.1 WPF Application 1. Introduction This article will be useful to show the basic concepts of Prism and apply them to create a Prism solution that we can use as the starting point for building a composite Windows Presentation Foundation (WPF) application. The points of this article collection are: Create a new solution based. Create and load a module. Create a view. Create a region MVVM: Interaction between View, View Model, and Model classes Navigation Communication between modules WPF (constructing a high-level view) 2. Prism Background Prism provides guidance designed to help more easily design and build rich, flexible, and easily maintained Windows Presentation Foundation (WPF) desktop applications, Silverlight Rich Internet Applications (RIAs), and Windows Phone 7 applications. Using design patterns that embody important architectural design principles, such as separation of concerns and loose coupling, Prism helps to design and build applications using loosely coupled components that can evolve independently but which can be easily and seamlessly integrated into the overall application. These types of applications are known as composite applications. The guidance is designed to help architects and developers achieve the following objectives: Create an application from modules that can be built, assembled and, optionally, deployed by independent teams using WPF or Silverlight. Minimize cross-team dependencies and allow teams to specialize in different areas, such as user interface (UI) design, business logic implementation, and infrastructure code development. Use an architecture that promotes reusability across independent teams. Increase the quality of applications by abstracting common services that are available to all the teams. Incrementally integrate new capabilities.

Upload: manthonee

Post on 31-Dec-2015

133 views

Category:

Documents


1 download

DESCRIPTION

This article will be useful to show the basic concepts of Prism and apply them to create a Prism solution that we can use as the starting point for building a composite Windows Presentation Foundation (WPF) application.

TRANSCRIPT

Page 1: Microsoft Prism WPF Application

Prism 4.1 Developer Guide – For Beginners

Microsoft Prism 4.1 WPF Application

1. Introduction

This article will be useful to show the basic concepts of Prism and apply them to create a Prism solution that we can use as the starting point for building a composite Windows Presentation Foundation (WPF) application. The points of this article collection are:

Create a new solution based. Create and load a module. Create a view. Create a region MVVM: Interaction between View, View Model, and Model classes Navigation Communication between modules WPF (constructing a high-level view)

2. Prism Background

Prism provides guidance designed to help more easily design and build rich, flexible, and easily maintained Windows Presentation Foundation (WPF) desktop applications, Silverlight Rich Internet Applications (RIAs), and Windows Phone 7 applications. Using design patterns that embody important architectural design principles, such as separation of concerns and loose coupling, Prism helps to design and build applications using loosely coupled components that can evolve independently but which can be easily and seamlessly integrated into the overall application. These types of applications are known as composite applications. The guidance is designed to help architects and developers achieve the following objectives:

Create an application from modules that can be built, assembled and, optionally, deployed by independent teams using WPF or Silverlight.

Minimize cross-team dependencies and allow teams to specialize in different areas, such as user interface (UI) design, business logic implementation, and infrastructure code development.

Use an architecture that promotes reusability across independent teams. Increase the quality of applications by abstracting common services that are available to all the teams. Incrementally integrate new capabilities.

Page 2: Microsoft Prism WPF Application

Prism 4.1 Developer Guide – For Beginners

2

Most Prism applications consist of a shell application that defines regions for displaying top-level views and shared services that can be accessed by the loaded modules. The shell defines a suitable catalog to specify which modules are to be loaded at startup time or on-demand, as appropriate. A dependency injection container is also defined, which allows component dependencies to be fulfilled at run time. Shared services and components are registered with the container by the Bootstrapper when the application starts. Individual modules encapsulate a portion of the overall application's functionality and, using a separated presentation pattern such as MVVM, define views, view models, models, and service components. When the modules are loaded, views defined within the modules are displayed within the regions defined by the shell. After initialization completes, the user then navigates within the application using state-based or view-switching navigation to coordinate the visual update or display of new views within the application's regions.

Page 3: Microsoft Prism WPF Application

Prism 4.1 Developer Guide – For Beginners

3

PRISM is a framework for developing composite application. It helps to develop a complex application breaking it down into smaller and manageable pieces and also is specific for WPF, Silverlight and windows Phone 7. This framework is based on design patterns that promote loose coupling and separation of concerns.

3. Advantages of Using Prism

Reuse Extensibility Flexibility Supports Team Development Quality of code

Page 4: Microsoft Prism WPF Application

Prism 4.1 Developer Guide – For Beginners

4

4. Shell

The application shell provides the basic layout for the application. This layout is defined using regions that modules can use to place views. Views, like shells, can use regions to define discoverable areas that content can be added to, as shown in the following illustration. Shells typically set the appearance for the entire application and contain the styles that are used throughout the application.

Page 5: Microsoft Prism WPF Application

Prism 4.1 Developer Guide – For Beginners

5

5. BootStrapper

The bootstrapper is the glue that connects the application with the Prism Library services and the Unity or MEF containers. Each application creates an application-specific bootstrapper, which typically inherits from either UnityBootstrapper or MefBootstrapper, as shown in the following illustration. We will need to decide the approach we want to use to populate the module catalog. Minimally, each application will provide a module catalog and a shell. By default, the bootstrapper logs events using the .NET Framework Trace class. Most applications will want to supply their own logging services, such as Enterprise Library logging. Applications can supply their logging service in their bootstrapper. By default, the UnityBootstrapper and MefBootstrapper enable the Prism Library services. These can be disabled or replaced in our application-specific bootstrapper.

Page 6: Microsoft Prism WPF Application

Prism 4.1 Developer Guide – For Beginners

6

6. Modules

The module contains the views and services specific to a piece of the application's functionality. Frequently, these are contained in separate assemblies and developed by separate teams. A module is denoted by a class that implements the IModule interface. These modules, during initialization, register their views and services and may add one or more views to the shell. Depending on module discovery approach, we may need to apply attributes to module classes or define dependencies between modules. Modules take advantage of the shell's regions for placing content. During initialization, modules use the RegionManager to locate regions in the shell and add one or more views to those regions or register one or more view types to be created within those regions. The RegionManager is responsible for keeping track of regions throughout the application and is a core service initialized from the bootstrapper.

7. Regions A Region is a "Placeholder" for dynamic content that is going to be presented in UI or in Shell. It's analogous to the concept of the content placeholder in the ASP.NET Master Page. More specifications of the Region component:

Regions can be defined in the Shell or in another View. Regions have no knowledge of views i.e. we can locate and add content to a Region without exact

knowledge of how and where that Region is defined. This allows the appearance and layout to change affecting only the module or View.

Region can be created in code or in XAML. A Region implements IRegion interface (important when adding programmatically access to the Region).

The Region Manager is the responsible for managing Regions in the application:

Maintains the collection of Regions Provides a RegionName attached property, Maps RegionAdapter to controls (RegionAdapter is basically responsible for associating a Region with the

host it controls). RegionAdapter that PRISM provides to us are: o ContentControlRegionAdapter: Adapts controls of type content control. o ItemsControlRegionAdapter: Adapts controls of type items control. o SelectorRegionAdapter: Adapts controls of type selector (like tabs).

Provides a RegionContext attached property, is like a dataContext. It's the technique to share the data between the parent View and the Child View.

Page 7: Microsoft Prism WPF Application

Prism 4.1 Developer Guide – For Beginners

7

8. Initiation Steps – Prism WPF Application

Download Prism 4.1 Library from the path http://www.microsoft.com/en-sg/download/details.aspx?id=28950 and Install the library on your local machine.

Once downloaded, extract the files from Prism4.1_Source.EXE and select the folder C:\PRISM4.1 .There are a lot of files inside but we only need the location of the PRISM library files in folder .\Bin\Desktop.

In Visual Studio 2010, Go to File --> New --> Project… -->Select WPF Application, and choose the folder

and press OK.

Page 8: Microsoft Prism WPF Application

Prism 4.1 Developer Guide – For Beginners

8

Add Reference to the Prism Libraries.

By default, Visual Studio 2010 uses the name MainWindow.xaml for the main file. Delete it and then open the file App.xaml and remove the attribute

StartupUri="MainWindow.xaml" By doing this App.xaml will look like as: <Application x:Class="CS.Config2DB.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Application.Resources> </Application.Resources> </Application>

Override On Start Up Method in the App.xaml.cs class to run the BootStrapper.

protected override void OnStartup(StartupEventArgs e)

{ base.OnStartup(e); // The boostrapper will create the Shell instance, // so the App.xaml does not have a StartupUri. var bootstrapper = new BootStrapper(); bootstrapper.Run(); }

Page 9: Microsoft Prism WPF Application

Prism 4.1 Developer Guide – For Beginners

9

The shell is the 'main window' of our application; it contains the visual elements that define the overall layout and style of our applications like the Master Page in ASP.NET. For the creation of the Shell, Add new item to the Prism Application project and select new Window and set the name to Shell.xaml

Create BootStrapper Class responsible for the initialization of an application built using the Prism Library. By using a bootstrapper, we have more control of how the Prism Library components are wired up to our application.

Page 10: Microsoft Prism WPF Application

Prism 4.1 Developer Guide – For Beginners

10

Select the Container for implementing the BootStrapper class. For Unity Container, inherit the BootStrapper class from UnityBootstrapper class and implement Create

Shell Method.

public class Bootstrapper : UnityBootstrapper { protected override System.Windows.DependencyObject CreateShell() { return this.Container.Resolve<Shell>(); } }

For MEF Container, inherit the BootStrapper class from MefBootstrapper class and implement Create Shell Method.

public class Bootstrapper : MefBootstrapper { protected override System.Windows.DependencyObject CreateShell() { return this.Container.GetExportedValue<Shell>(); } }

Export Shell class to be present in the container only when MefBootstrapper is used.

[Export]

public partial class Shell : Window

Implement Initialize Shell Method in the BootStrapper class.

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

Override Configure Aggregate Catalog Method in the BootStrapper to aggregate modules in the catalog.

public class Bootstrapper : MefBootstrapper { protected override void ConfigureAggregateCatalog() { base.ConfigureAggregateCatalog(); // Add this assembly to export ModuleTracker this.AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(BootStrapper).Assembly)); } }

Page 11: Microsoft Prism WPF Application

Prism 4.1 Developer Guide – For Beginners

11

Start creating a Module, select in the Solution Explorer the Folder Modules and right-click ->Add -> New Project... and select WPF User Control Library.

Once WPF User Control Project gets created, delete the file UserControl1.xaml, and add References to the PRISM libraries to use the IModule interface. Next step is to Add a new class to the Module, called Module that is going to implements IModule interface, so we need the Modularity package.

To register the View in its container. In order to does that open the Module.cs file and start implementing the Initialize method from IModule interface.

For Unity Container Implementation, Please refer below mentioned code.

namespace MenuModule { public class Module : IModule { IUnityContainer _container; public Module(IUnityContainer container) { _container = container; } public void Initialize() { _container.RegisterType<ToolbarA>(); _container.RegisterType<ContentA>(); } } }

Page 12: Microsoft Prism WPF Application

Prism 4.1 Developer Guide – For Beginners

12

To Register a module using Unity Container, first step is to add a Reference to the Module Project in the Prism Application project. Once added, we edit the Bootstrapper class and override the ConfigureModuleCatalog Method, then add the following line to use ModuleCatalog Entity and Module.

protected override void ConfigureModuleCatalog() { base.ConfigureModuleCatalog(); ModuleCatalog moduleCatalog = (ModuleCatalog)this.ModuleCatalog; moduleCatalog.AddModule(typeof(ModuleAModule)); }

When using MEF, the MefModuleManager is used by the MefBootstrapper. It extends the

ModuleManager and implements the IPartImportsSatisfiedNotification interface to ensure that the ModuleCatalog is updated when new types are imported by MEF.

When using MEF, we can apply the Module Export attribute to module classes to have MEF automatically discover the types. The following is an example.

[ModuleExport(typeof(MenuModule))]

public class MenuModule : IModule {

}

By default, the Prism MefBootstrapper class creates an AggregateCatalog instance. We can then override

the ConfigureAggregateCatalog method to register assemblies.

protected override void ConfigureAggregateCatalog() { base.ConfigureAggregateCatalog(); // Add this assembly to export ModuleTracker this.AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(BootStrapper).Assembly)); // Menu Module is referenced in in the project and directly in code. this.AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(MenuModule.MenuModule).Assembly)); }

The Prism MefModuleManager implementation keeps the MEF AggregateCatalog and the Prism

ModuleCatalog synchronized, thereby allowing Prism to discover modules added via the ModuleCatalog or the AggregateCatalog.

MEF provides a DirectoryCatalog that can be used to inspect a directory for assemblies containing modules (and other MEF exported types). In this case, we override the ConfigureAggregateCatalog method to register the directory. This approach is only available in WPF.

protected override void ConfigureAggregateCatalog()

{

base.ConfigureAggregateCatalog();

DirectoryCatalog catalog = new

DirectoryCatalog("DirectoryModules");

this.AggregateCatalog.Catalogs.Add(catalog);

}

Page 13: Microsoft Prism WPF Application

Prism 4.1 Developer Guide – For Beginners

13

To register Module’s View with the Region specified in Shell, Use Region Manager. For Unity Container, Please refer the below mentioned sample code.

namespace MenuModule { public class MenuModule : IModule { IUnityContainer _container; IRegionManager _manager; public ModuleAModule(IUnityContainer container, IRegionManager manager) { _container = container; _manager = manager; } public void Initialize() { _container.RegisterType<MenuView>(); _container.RegisterType<MenuViewModel>(); _manager.RegisterViewWithRegion(RegionNames.MenuRegion, typeof(MenuView)); } } }

For MEF Container, Please refer the below mentioned sample code.

namespace MenuModule { public class MenuModule : IModule { [Import] private IRegionManager regionManager; public void Initialize() { this.regionManager.RegisterViewWithRegion(RegionNames.MenuRegion, typeof(MenuView)); } } }

Page 14: Microsoft Prism WPF Application

Prism 4.1 Developer Guide – For Beginners

14

The Prism Library provides an event mechanism that enables communications between loosely coupled components in the application. This mechanism, based on the event aggregator service, allows publishers and subscribers to communicate through events and still do not have a direct reference to each other.

The EventAggregator provides multicast publish/subscribe functionality. This means there can be multiple publishers that raise the same event and there can be multiple subscribers listening to the same event. Consider using the EventAggregator to publish an event across modules and when sending a message between business logic code, such as controllers and presenters.

public interface IEventAggregator

{

TEventType GetEvent<TEventType>() where TEventType : EventBase;

}

// Event Publishing this.eventAggregator.GetEvent<EventName>().Publish("RAHUL");

// Event Subscription this.eventAggregator.GetEvent<EventName>().Subscribe(SubscribingMethod,

ThreadOption.UIThread);