Creating a WPF Application using Prism Library and MVVM Architectural Pattern (2024)

  • Rikam Palkar
  • Dec 12, 2019
  • 238.4k
  • 0
  • 4

My_First_WPF_App.zip

Introduction

This blog explains how to develop a WPF application using a Prism library and MVVM architectural pattern. No matter how big or complex your app is, this base foundation stays the same for all types of projects. That's why it's very crucial to understand its behavior. We will learn how to make use of UnityContainer and how to achieve modularity in WPF applications using Prism.

Why Prism? Prism is a framework for building loosely coupled, maintainable, and testable XAML applications in WPF.

Note: There is a project download attached for your reference. The source code is free to use and developed only for learning purposes.

Steps

  1. Start Visual Studio, Click on create WPF APP (.Net Framework) : give a name to your app as you desire. As this is a demo project, I have chosen My_First_WPF_App (Refer to the below image.)

    Creating a WPF Application using Prism Library and MVVM Architectural Pattern (3)

  2. Right-click on your project (not the solution) and add a new window into your My_First_WPF_App project. Name your window Shell.xaml. Shell is your Master layout: It's going to load regions for your WPF App. You can delete MainWindow.xaml or can rename as Shell.xaml
    (Refer to the below image.)

    Creating a WPF Application using Prism Library and MVVM Architectural Pattern (4)

  3. Let's begin with Prism's installation: Add Prism.Unity using the Nuget package manager into your shell project. Right-click on the project and click on the Nuget Package manager (Refer to the below image). Then hit install. This will install Prism libraries into your project.

    Creating a WPF Application using Prism Library and MVVM Architectural Pattern (5)

  4. After the successful installation of Prism.unity. Expand your project's references to check if prism libraries are added or not.
    (Refer below image.)

    Creating a WPF Application using Prism Library and MVVM Architectural Pattern (6)

  5. Now that we have an entrypoint - Shell.Xaml, from where we're going to start loading our modules, we need a class to load the shell. For that, we're going to add the class into My_First_WPF_App Project and name it BootStrapper.
  6. Note : Make the BootStrapper class Public and inherit from UnityBootStapper Class,
    UnityBootStapper class coming from namespace: using Prism.Unity;
  • Override Run() method,
  • Override CreateShell() method,
  • Override InitializeShell() method,
  • Override ConfigureModuleCatalog() method
  • (Refer below code snippet.)
    1. usingSystem;
    2. usingSystem.Windows;
    3. usingPrism.Unity;
    4. namespaceMy_First_WPF_App
    5. {
    6. ///<summary>
    7. ///BootStrapperisresponsibleforloadingprismandinitializingShell.
    8. ///</summary>
    9. [Obsolete]
    10. publicclassBootStrapper:UnityBootstrapper
    11. {
    12. #regionOverriddenMethods
    13. ///<summary>
    14. ///Entrypointtotheapplication
    15. ///</summary>
    16. ///<paramname="runWithDefaultConfiguration"></param>
    17. publicoverridevoidRun(boolrunWithDefaultConfiguration)
    18. {
    19. base.Run(runWithDefaultConfiguration);
    20. }
    21. ///<summary>
    22. ///Initializesshell.xaml
    23. ///</summary>
    24. ///<returns></returns>
    25. protectedoverrideDependencyObjectCreateShell()
    26. {
    27. returnContainer.TryResolve<Shell>();
    28. }
    29. ///<summary>
    30. ///loadstheShell.xaml
    31. ///</summary>
    32. protectedoverridevoidInitializeShell()
    33. {
    34. App.Current.MainWindow=(Window)Shell;
    35. App.Current.MainWindow.Show();
    36. }
    37. ///<summary>
    38. ///Addview(module)fromotherassembliesandbeginswithmodularity
    39. ///</summary>
    40. protectedoverridevoidConfigureModuleCatalog()
    41. {
    42. base.ConfigureModuleCatalog();
    43. }
    44. #endregion
    45. }
    46. }
  • Build your project once to make sure there are no errors so far.
  • Open App.xaml and delete, StartupUri="MainWindow.xaml" - As your project's default startup window is MainWindow but we've deleted or renamed it. Now we want our app's entry point to be Shell.xaml
    Open the code-behind of App.xaml which is App.xaml.cs and create an object of BootStrapper.
    (Refer bold part of below code snippet.)
    1. usingSystem.Windows;
    2. namespaceMy_First_WPF_App
    3. {
    4. ///<summary>
    5. ///InteractionlogicforApp.xaml
    6. ///</summary>
    7. publicpartialclassApp:Application
    8. {
    9. protectedoverridevoidOnStartup(StartupEventArgse)
    10. {
    11. base.OnStartup(e);
    12. BootStrapperbootStrapper=newBootStrapper();
    13. bootStrapper.Run();
    14. }
    15. }
    16. }
    Run your project and see the magic. Your project will load into the Shell window, now that we've got Shell as entry point.
  • Now that we have all the control towards Shell.xaml, it's time to add some Modularity to your project.
    1. Go to Shell.xaml
    2. First add the Prism Namespace : xmlns:prism="http://prismlibrary.com/"
    3. Create ItemsControl inside your grid : <ItemsControl prism:RegionManager.RegionName="Shell"/>

      (Refer bold part of below code snippet.)

      1. <Windowx:Class="My_First_WPF_App.Shell"
      2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      3. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      4. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      5. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      6. mc:Ignorable="d"
      7. xmlns:prism="http://prismlibrary.com/"
      8. Title="Shell"Height="450"Width="800">
      9. <Grid>
      10. <ItemsControlprism:RegionManager.RegionName="Shell"/>
      11. </Grid>
      12. </Window>
  • Now that we've set our main project, it's time to add some modules. As there are 3 basic modules of 3 -Tier Architecture. This is a demo project so we will create only one Presentation module which is Class Library (DLL). Right-click on Solution and add DLL to your Solution file. Name your DLL Presentation.
    (Refer below image.)

    Creating a WPF Application using Prism Library and MVVM Architectural Pattern (7)

  • Let's create View and ViewModels folders in this DLL. (It's the same way, right-click on presentation, Add new folder from submenu, rename as View. Follow same for ViewModel)
    • Add our first UserControl.xaml into View folder and name it WelcomePageView.Xaml(WPF).
    • In the same way, let's add C# class file into ViewModel folder and name it WelcomePageViewModel.cs
  • Add Prism into your newly created Presentation.dll, follow step 3.
  • Open WelcomePageView : Add namespaces, and set AutoWireViewModel to true inside UserControl tag
    (Refer bold part of below code snippet.)
    1. <UserControlx:Class="Presentation.View.WelcomePageView"
    2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    3. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    4. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    5. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    6. xmlns:prism="http://prismlibrary.com/"
    7. prism:ViewModelLocator.AutoWireViewModel="True"
    8. mc:Ignorable="d"
    9. d:DesignHeight="450"d:DesignWidth="800">
  • Now we need the Module Locator, so add a C# class and name it as ModuleLocators.cs inside Presentation.dll Project
    1. Inherit class from Imodule interface from using Prism.Modularity;
    2. Implement Interface
    3. Create Instance of IRegionManager
    4. Create Parameterized Constructor and assign to instance
    5. Override OnInitialized method , can leave the RegisterTypes empty for now.
      (Refer below code snippet.)
      1. usingPrism.Ioc;
      2. usingPrism.Modularity;
      3. usingPrism.Regions;
      4. namespacePresentation
      5. {
      6. ///<summary>
      7. ///Responsibleformappingmodules
      8. ///</summary>
      9. publicclassModuleLocators:IModule
      10. {
      11. #regionprivateproperties
      12. ///<summary>
      13. ///InstanceofIRegionManager
      14. ///</summary>
      15. privateIRegionManager_regionManager;
      16. #endregion
      17. #regionConstructor
      18. ///<summary>
      19. ///parameterizedconstructorinitializesIRegionManager
      20. ///</summary>
      21. ///<paramname="regionManager"></param>
      22. publicModuleLocators(IRegionManagerregionManager)
      23. {
      24. _regionManager=regionManager;
      25. }
      26. #endregion
      27. #regionInterfacemethods
      28. ///<summary>
      29. ///InitializesWelcomepageofyourapplication.
      30. ///</summary>
      31. ///<paramname="containerProvider"></param>
      32. publicvoidOnInitialized(IContainerProvidercontainerProvider)
      33. {
      34. _regionManager.RegisterViewWithRegion("Shell",typeof(ModuleLocators));//ModuleLocatorsisaddedfortestingpurpose,
      35. //laterwe'llreplaceitwithWelcomePageView
      36. }
      37. ///<summary>
      38. ///RegisterTypesusedtoregistermodules
      39. ///</summary>
      40. ///<paramname="containerRegistry"></param>
      41. publicvoidRegisterTypes(IContainerRegistrycontainerRegistry)
      42. {
      43. }
      44. #endregion
      45. }
      46. }
  • Let's add the presentation module's reference into (My_First_WPF_App) project. Right click on references of My_First_WPF_App and click on add references, then go to projects and select Presentation. Hit OK.
    (Refer to the image below.)

    Creating a WPF Application using Prism Library and MVVM Architectural Pattern (8)

  • Now its time to tell BootStrapper which module it should look for. Open BootStapper.cs, Inside ConfigureModuleCatalog.
    (Refer to the bold part of the below code snippet.)
    1. usingSystem;
    2. usingSystem.Windows;
    3. usingPrism.Unity;
    4. namespaceMy_First_WPF_App
    5. {
    6. ///<summary>
    7. ///BootStrapperisresponsibleforloadingprismandinitializingShell.
    8. ///</summary>
    9. [Obsolete]
    10. publicclassBootStrapper:UnityBootstrapper
    11. {
    12. #regionOverriddenMethods
    13. ///<summary>
    14. ///Entrypointtotheapplication
    15. ///</summary>
    16. ///<paramname="runWithDefaultConfiguration"></param>
    17. publicoverridevoidRun(boolrunWithDefaultConfiguration)
    18. {
    19. base.Run(runWithDefaultConfiguration);
    20. }
    21. ///<summary>
    22. ///Initializesshell.xaml
    23. ///</summary>
    24. ///<returns></returns>
    25. protectedoverrideDependencyObjectCreateShell()
    26. {
    27. returnContainer.TryResolve<Shell>();
    28. }
    29. ///<summary>
    30. ///loadstheShell.xaml
    31. ///</summary>
    32. protectedoverridevoidInitializeShell()
    33. {
    34. App.Current.MainWindow=(Window)Shell;
    35. App.Current.MainWindow.Show();
    36. }
    37. ///<summary>
    38. ///Addview(module)fromotherassembliesandbeginswithmodularity
    39. ///</summary>
    40. protectedoverridevoidConfigureModuleCatalog()
    41. {
    42. base.ConfigureModuleCatalog();
    43. TypeModuleLocatorType=typeof(Presentation.ModuleLocators);
    44. ModuleCatalog.AddModule(newPrism.Modularity.ModuleInfo
    45. {
    46. ModuleName=ModuleLocatorType.Name,
    47. ModuleType=ModuleLocatorType.AssemblyQualifiedName
    48. });
    49. }
    50. #endregion
    51. }
    52. }
  • Now go to your ModuleLocators class of Presentation module. On the inside method, OnInitialized(), change type from NewlyCreatedView to WelcomePageView.
    (Refer to the bold part of the below code snippet.)
    1. usingPrism.Ioc;
    2. usingPrism.Modularity;
    3. usingPrism.Regions;
    4. namespacePresentation
    5. {
    6. ///<summary>
    7. ///Responsibleformappingmodules
    8. ///</summary>
    9. publicclassModuleLocators:IModule
    10. {
    11. #regionproperties
    12. ///<summary>
    13. ///InstanceofIRegionManager
    14. ///</summary>
    15. privateIRegionManager_regionManager;
    16. #endregion
    17. #regionConstructor
    18. ///<summary>
    19. ///parameterizedconstructorinitializesIRegionManager
    20. ///</summary>
    21. ///<paramname="regionManager"></param>
    22. publicModuleLocators(IRegionManagerregionManager)
    23. {
    24. _regionManager=regionManager;
    25. }
    26. #endregion
    27. #regionInterfacemethods
    28. ///<summary>
    29. ///InitializesWelcomepageofyourapplication.
    30. ///</summary>
    31. ///<paramname="containerProvider"></param>
    32. publicvoidOnInitialized(IContainerProvidercontainerProvider)
    33. {
    34. _regionManager.RegisterViewWithRegion("Shell",typeof(View.WelcomePageView));
    35. }
    36. ///<summary>
    37. ///RegisterTypesusedtoregistermodules
    38. ///</summary>
    39. ///<paramname="containerRegistry"></param>
    40. publicvoidRegisterTypes(IContainerRegistrycontainerRegistry)
    41. {
    42. }
    43. #endregion
    44. }
    45. }
  • Add a Textblock inside WelcomePageView to see if it's working properly.
    (Refer to the bold part of the below code snippet.)
    1. <UserControlx:Class="Presentation.View.WelcomePageView"
    2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    3. xmlns:prism="http://prismlibrary.com/"
    4. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    5. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    6. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    7. mc:Ignorable="d"
    8. prism:ViewModelLocator.AutoWireViewModel="True"
    9. d:DesignHeight="450"d:DesignWidth="800">
    10. <Grid>
    11. <TextBlockText="YousuccessfullyhaveconfiguredPrismintoyourAPP"/>
    12. </Grid>
    13. </UserControl>
  • Build and run your project. You'll get following output screen:
    (Refer to the image below.)

    Creating a WPF Application using Prism Library and MVVM Architectural Pattern (9)

  • Until now, we've added Prism into our project and we've finally achieved modularity. One final step left is having view communicate with viewmodel using MVVM pattern. We will achieve that with DataContext.
  • Let's add one more textblock into our WelcomePageView and bind it using a string property from our WelcomePageViewModel.
    (Refer to the bold part of the below code snippet.)
    1. <UserControlx:Class="Presentation.View.WelcomePageView"
    2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    3. xmlns:prism="http://prismlibrary.com/"
    4. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    5. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    6. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    7. mc:Ignorable="d"
    8. prism:ViewModelLocator.AutoWireViewModel="True"
    9. d:DesignHeight="450"d:DesignWidth="800">
    10. <Grid>
    11. <Grid.RowDefinitions>
    12. <RowDefinition/>
    13. <RowDefinition/>
    14. </Grid.RowDefinitions>
    15. <TextBlockText="YousuccessfullyhaveconfiguredPrismintoyourAPP"/>
    16. <TextBlockText="{BindingImGoodByeText}"Grid.Row="1"/>
    17. </Grid>
    18. </UserControl>
    1. usingSystem;
    2. namespacePresentation.ViewModel
    3. {
    4. ///<summary>
    5. ///ViewModelofWelcomePage,responsibleforlogicforrespectedview.
    6. ///</summary>
    7. publicclassWelcomePageViewModel
    8. {
    9. #regionProperties
    10. ///<summary>
    11. ///Thisstringpropertywillhavedefaulttextfordemopurpose.
    12. ///</summary>
    13. privatestring_imGoodByeText="ThisisbindedfromWelcomePageViewModel,ThankyouforbeingpartofthisBlog!";
    14. ///<summary>
    15. ///ThisstringpropertywillbebindedwithTextblockonview
    16. ///</summary>
    17. publicstringImGoodByeText
    18. {
    19. get{return_imGoodByeText;}
    20. set{_imGoodByeText=value;}
    21. }
    22. #endregion
    23. }
    24. }
  • And now open code behind WelcomePageView, so that we can set datacontext property from constructor.
    1. usingPresentation.ViewModel;
    2. usingSystem.Windows.Controls;
    3. namespacePresentation.View
    4. {
    5. ///<summary>
    6. ///InteractionlogicforWelcomePageView.xaml
    7. ///</summary>
    8. publicpartialclassWelcomePageView:UserControl
    9. {
    10. publicWelcomePageView()
    11. {
    12. InitializeComponent();
    13. this.DataContext=newWelcomePageViewModel();
    14. }
    15. }
    16. }
  • Now build and run your project, you'll get final output as below image.
    (Refer to the image below.)

    Creating a WPF Application using Prism Library and MVVM Architectural Pattern (10)

  • Thank you so much for visiting this blog, I hope you were helped by this. If you have any queries, please connect with me.

    Have a good day :)

    Creating a WPF Application using Prism Library and MVVM Architectural Pattern (2024)
    Top Articles
    Latest Posts
    Article information

    Author: Van Hayes

    Last Updated:

    Views: 6339

    Rating: 4.6 / 5 (66 voted)

    Reviews: 89% of readers found this page helpful

    Author information

    Name: Van Hayes

    Birthday: 1994-06-07

    Address: 2004 Kling Rapid, New Destiny, MT 64658-2367

    Phone: +512425013758

    Job: National Farming Director

    Hobby: Reading, Polo, Genealogy, amateur radio, Scouting, Stand-up comedy, Cryptography

    Introduction: My name is Van Hayes, I am a thankful, friendly, smiling, calm, powerful, fine, enthusiastic person who loves writing and wants to share my knowledge and understanding with you.