WPF Prism Framework (MVVM)

Introduction to Prism

Modules: Modules are functional units that can be developed, tested, and deployed independently. Modules can be designed as modules that implement specific business logic (such as Profile Management), or as modules that implement general infrastructure or services (such as Logging, Exception Management).
Module Catalog: In Prism, the Module Catalog specifies which Modules to load and the order in which to load these Modules.
Shell: Shell is the host application, and modules will be loaded into the Shell. The Shell defines the overall layout and structure of the application without caring about the Modules that host it. The Shell usually implements general application services and infrastructure, while the application logic is implemented in specific Modules. At the same time, the Shell also provides the application's Top level window.
Views: Views are views in the application that display specific functions. They display the UI, define interactive behaviors, and interact with the ViewModel through data binding.
ViewModel and Presenters: View Model is used to encapsulate the UI logic of the application and its state.
Model: Model is used to encapsulate data and corresponding verification, as well as related business rules to ensure the consistency and correctness of the data.
Commands: Command is used to encapsulate application functions. Prism provides two classes: DelegateCommand and CompositeCommand.
Regions: Regions are logical areas of the application UI. It is much like a PlaceHolder. Views are displayed in Regions. Many types of controls can be used as Regions: ContentControl, ItemsControl, ListBox, and TabControl. Views can be programmed or automatically rendered in Regions, and Prism also provides support for Region navigation.

Introduction to MVVM

MVVM is the abbreviation of Model-View-ViewModel. It is essentially an improved version of MVC.

In order to comply with the idea of ​​"high cohesion and low coupling", the MVC three-tier architecture divides each functional module into a three-tier architecture of presentation layer (UI), business logic layer (BLL) and data access layer (DAL). Interfaces are used to access each other, and the entity classes (Model) of the object model are used as the carrier of data transfer. The entity classes of different object models generally correspond to different tables in the database, and the attributes of the entity classes are consistent with the field names of the database tables.
The purpose of distinguishing levels in a three-tier architecture is for "high cohesion and low coupling". Developers have a clearer division of labor and focus more on the analysis, design and development of the core business logic of the application system, speeding up the progress of the project, improving development efficiency, and conducive to project updates and maintenance.
1. Interface layer (UI)
The interface layer provides users with a visual interface. Through the interface layer, users input and obtain data. The interface layer also provides a certain level of security to ensure that users do not see unnecessary confidential information.
2. Logic layer (BLL)
The logic layer is the bridge between the interface layer and the data layer. It responds to user requests from the interface layer, performs tasks and captures data from the data layer, and transmits the necessary data to the interface layer.
3. Data Layer (DAL)
The data layer defines and maintains data integrity and security. It responds to requests from the logic layer and accesses data.

MVVM abstracts the state and behavior of the View, allowing us to separate the view UI and business logic.

MVVM is Model-View-ViewModel. The model refers to the data passed by the backend; the view refers to the page you see. The view model is the core of the mvvm pattern. It is the bridge connecting the view and the model. It has two directions: one is to convert the model into a view, that is, convert the data passed by the backend into the page you see. The way to achieve this is: data binding. The second is to convert the view into a model, that is, convert the page you see into back-end data. The way to implement it is: DOM event listening. Implementing both directions is called two-way binding of data.

Prior to this, WPF generally used the MVVMLight (obsolete) package to introduce the MVVM framework, and later used the Microsoft toolkit mvvm (obsolete). Nowadays, CommunityToolkit.Mvvm or Prism is often used to introduce the MVVM framework.

To introduce the Prism framework, use the Prism.DryIoc.Forms package

Add prism dependency in the App.xaml namespace: xmlns:prism="http://prismlibrary.com/". Modify the Application tag in the App.xaml file to prism:PrismApplication. (The wfp project uses the Application object, and the project using the prism framework uses PrismApplication. How does the Application object start the main page, StartupUri, PrismApplication can start the main page with StartupUri (can be deleted), or not. It is recommended to use App .xaml Dependency injection in the CreateShell() method in .cs)

<prism:PrismApplication x:Class="PrismDemo.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:PrismDemo"
             xmlns:prism="http://prismlibrary.com/">
    <Application.Resources>
    </Application.Resources>
</prism:PrismApplication>


Create Views and ViewModels folders, and move the MainWindow.xaml view file automatically created when the project is created to the Views folder (don’t forget to modify the namespaces in MainWindow.xaml and MainWindow.xaml.cs, add .Views )
 

<Window x:Class="Demo1.MainWindow"></Window>
修改为:
<Window x:Class="Demo1.Views.MainWindow"></Window>
修改App.xaml.cs继承的类,将继承的Window类改成PrismApplication类,实现PrismApplication类中的CreateShell()方法和RegisterTypes()方法
namespace PrismDemo
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : PrismApplication
    {
        // 关系:PrismApplication 继承于 PrismApplicationBase 继承于 Application
        // 快捷键:查看对象源码:fn+f12,快速实现接口,方法,抽象类:alt+enter+enter
        // 快速创建构造函数:ctor
 
        // Window窗体, StartupUri可以启动一个窗体
        // CreateShell()主要负责启动一个主页面。Main
        protected override Window CreateShell()
        {
            // 启动一个窗体MainWindow
            return Container.Resolve<Main>();
        }
 
        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
        }
       
    }
}

The advantage of Prism used to implement MVVM over CommunityToolkit.Mvvm is that the former can be automatically bound, while the latter can only be bound manually.

Conditions that need to be met for Prism automatic binding:

  • Form | Page | User Control must be placed in the Views folder
  • The model must be placed in the ViewModels folder
  • The name of the model name must start with the form name and end with ViewModel

 

 Code in xaml:

<Window x:Class="PrismWpf.Views.a"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      xmlns:local="clr-namespace:PrismWpf.Views"
      xmlns:prism="http://prismlibrary.com/"
      prism:ViewModelLocator.AutoWireViewModel="True"
      mc:Ignorable="d" 
      d:DesignHeight="450" d:DesignWidth="800"
      Title="a">

    <Grid>
        <TextBlock Text="a页面"/>
        <TextBlock Width="50" Height="50" Text="{Binding Age}"  FontSize="20"/>
    </Grid>
</Window>

Code in ViewModel:

namespace PrismWpf.ViewModels
{
    public class aViewModel 
    {
        private int _id;
        public int Age
        {
            get
            {
                return _id;
            }
            set
            {
                _id = value;
             
            }
        }

        aViewModel()
        {
            Age = 50;
        }
    }
}

Manual binding requires adding an instantiation of aViewModel in a.xaml.cs and binding the data context to it.

namespace PrismWpf.Views
{
    /// <summary>
    /// a.xaml 的交互逻辑
    /// </summary>
    public partial class a : Window
    {
        public a()
        {
            InitializeComponent();
            aViewModel aViewModel = new aViewModel();
            this.DataContext = aViewModel;
        }
    }
}

Guess you like

Origin blog.csdn.net/qq_57212959/article/details/131995061