C# WPF MVVM模式Prism框架从零搭建(经典)


01

 

前言

 

目前最新的PRISM的版本是8.1.97,本节以6.3.0.0 讲解,可以在Github上获取PRISM的源码。

  • Prism Github地址:https://github.com/PrismLibrary/Prism

  • Prism官方文档:https://prismlibrary.com/docs/

  • Prism要用到IOC容器,提供选择的有Unity和MEF,这里我分别采用MEF和unity去做,不懂MEF的建议看看这位大牛的系列博文http://www.cnblogs.com/yunfeifei/p/3922668.html

 

 

02

安装库

 

在nuget上安装Prism相关常用的库

 

 

 

 

03

 

项目搭建

step1:新建解决方案:我这里命名为PrismFrameTest;

step2:删除MainWindow.xaml,删除App.xaml中启动引导

 StartupUri="MainWindow.xaml"

然后在App.xaml.cs新建程序入口

 protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            MyBootstrapper bootStrapper = new MyBootstrapper();
            bootStrapper.Run(true);
        }

新建引导类MyBootstrapper.cs,需要继承基类Prism.Mef库下的基类MefBootstrapper

 

方式1 采用mef

public class MyBootstrapper : MefBootstrapper
    {
        protected override DependencyObject CreateShell()
        {
            return this.Container.GetExportedValue<MyShellView>();
        }
        protected override void InitializeShell()
        {
            base.InitializeShell();
            Application.Current.MainWindow = (MyShellView)this.Shell;
            Application.Current.MainWindow.Show();//Show主窗口,但content内没有内容,只有当调用Module中的Initialize()方法后才将HelloWorldView显示出来。
        }
        protected override void ConfigureAggregateCatalog()
        {
            base.ConfigureAggregateCatalog();
            this.AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(MyBootstrapper).Assembly));
            this.AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(PrismModuleLeft.ModuleLeftViewModel).Assembly));//注册模块
            //this.AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(ModuleB.ModuleBViewModel).Assembly));
        }
        protected override IModuleCatalog CreateModuleCatalog()
        {
            // When using MEF, the existing Prism ModuleCatalog is still the place to configure modules via configuration files.
            return new ConfigurationModuleCatalog();
        }

    }

方式2 采用unity

public class MyBootstrapper : UnityBootstrapper
    {
        protected override DependencyObject CreateShell()
        {
            return Container.Resolve<MyShellView>();
        }

        protected override void InitializeShell()
        {
            base.InitializeShell();

            Application.Current.MainWindow = (MyShellView)this.Shell;
            Application.Current.MainWindow.Show();//Show主窗口,但content内没有内容,只有当调用Module中的Initialize()方法后才将HelloWorldView显示出来。
        }

        protected override void ConfigureModuleCatalog()
        {
            base.ConfigureModuleCatalog();

            ModuleCatalog moduleCatalog = (ModuleCatalog)this.ModuleCatalog;
            moduleCatalog.AddModule(typeof(PrismModuleLeft.ModuleLeftViewModel));//注册模块
        }

    }

step3:

 

然后新建一个xaml窗体MyShellView.xaml,将窗体分为左右两部分

这里cal:RegionManager.RegionName是一个依赖属性,我们将它与ItemsControl控件相关联,MainRegion就是一个占位符。

 

 <ItemsControl cal:RegionManager.RegionName="RegionLeft" HorizontalAlignment="Center" VerticalAlignment="Center"/>
 <ItemsControl cal:RegionManager.RegionName="RegionRight" HorizontalAlignment="Center" VerticalAlignment="Center" Grid.Column="1"/>

对应的cs中将类标注为  [Export]

step4:新建类库PrismModuleLeft

类库中新建ModuleLeftView.xaml

关于事件绑定:(在下面代码中两种方式都列出来了)

①控件继承自ButtonBase、MenuItem类,比如:Button、RadioButton、Hyperlink、MenuItem……这种情况下,由于Prism已经帮我们实现了这些控件的Command属性,可以直接绑定Command属性来完成Click事件到ViewModel的绑定:

②ListView、ListBox、DropDownList等等大部分没有Click事件的控件。这时候,当我们要实现SelectedItemChanged、SelectionChanged等常用事件的时候,使用Expression Blend附带的System.Windows.Interactivity.dll文件,它使用interaction trigger和InvokeCommandAction behavior来帮助我们直接绑定控件的事件。

需要引用

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"

 <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <TextBlock  Foreground="Red" FontSize="20" Text="{Binding TxtLabel}" Background="Gray" Grid.Row="0"/>
        <Button Background="LightCyan" Name="CreateRecipe" Command="{Binding CreateRecipeCommand}" Content="BtnCtr" FontSize="20" Grid.Row="1">
            <i:Interaction.Triggers >
                <i:EventTrigger EventName="PreviewKeyDown">
                    <i:InvokeCommandAction Command="{Binding KeyUpEventCommand}" />
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </Button>
        </Grid>

对应的cs中:

 [Export]
    public partial class ModuleLeftView : UserControl
    {
        private readonly IRegionViewRegistry regionViewRegistry;
        public ModuleLeftView()
        {
            InitializeComponent();
            this.DataContext = new ModuleLeftViewModel(regionViewRegistry);
        }
    }

step4:ModuleLeftViewModel中:

using Prism.Commands;
using Prism.Mef.Modularity;
using Prism.Modularity;
using Prism.Mvvm;
using Prism.Regions;
using PropertyChanged;
using System.ComponentModel.Composition;
using System.Windows;
using System.Windows.Input;

namespace PrismModuleLeft
{
    [AddINotifyPropertyChangedInterface]
    [ModuleExport("ModuleLeftViewModel", typeof(ModuleLeftViewModel), InitializationMode = InitializationMode.WhenAvailable)]
    public class ModuleLeftViewModel : BindableBase,IModule
    {
        private readonly IRegionViewRegistry regionViewRegistry;
        public ICommand CreateRecipeCommand { get; set; }
        public DelegateCommand<KeyEventArgs> KeyUpEventCommand { get; private set; }
        public string TxtLabel { get; set; } = "Hello! I am ModuleA";
        public void KeyUpEventHandler(KeyEventArgs args)
        {
            MessageBox.Show("PrismCTR");
        }
        public void Initialize()
        {
            regionViewRegistry.RegisterViewWithRegion("RegionLeft", typeof(ModuleLeftView));

        }
        [ImportingConstructor]
        public ModuleLeftViewModel(IRegionViewRegistry registry)
        {
            this.regionViewRegistry = registry;
            CreateRecipeCommand = new DelegateCommand(() => CreateRecipe());         
        }
        public void CreateRecipe()
        {
            TxtLabel = "this is my first prism test example";
            MessageBox.Show(TxtLabel);
        }
    }
}

04

总结

 

这个时候我们来对PRISM的基础架构做一个简单的总结:

 

Shell: 主窗口,他的功能都是通过Module来实现的;

 

Bootstrapper: 应用程序的入口点;

 

Region: 内容区域,类似于一个占位符

 

Module: 真正实现业务功能的东西,是View,数据,模型组成的集合;

 

Prism是个非常强大的wpf mvvm模式框架,它使用依赖注入,控制反转容器来帮助我们解决团队合作的松耦合问题。

 

05

结果演示

 

 

05

源码

 

链接:https://pan.baidu.com/s/1utVT-087R1WonjoHZrv_Iw

提取码:添加小编微信zls20210502获取

技术群: 需要进技术群的添加小编微信zls20210502 ,备注:加群;

文章来源:https://www.cnblogs.com/zls366/p/15611415.html

版权声明:本文为YES开发框架网发布内容,转载请附上原文出处连接
管理员
上一篇:C# 机器学习
下一篇:windows平台的分布式微服务解决方案(1)--UUID全球通用唯一识别码
评论列表

发表评论

评论内容
昵称:
验证码:
验证码
关联文章

C# WPF MVVM模式Prism框架(经典)
C# 值得永久收藏的WPF项目实战(经典)
走进WPFMVVM完整案例
阿里云服务器使用xlightftp服务器
使用 MVVM Toolkit Source Generators
RabbitMQ服务器环境方法(Windows)
Elasticsearch使用系列-ES简介和环境
阿里云FTP服务器访问报错 200,227错误
ASP.NET+MVC入门踩坑笔记 (一) 创建项目 项目配置运行 以及简单的Api
YESWEB开发环境
使用node启动本地项目,本地服务器
YESWin winform开发框架 开发环境指南
C# Abp框架入门系列文章(一)
TinyMCE 代码高亮 Prism.js 对 C# language-csharp 没做处理
ABP VNext框架基础知识介绍(1)--框架基础类继承关系
OrchardCore Headless
2.网络聊天程序的三种模式
dotnetCampus.UITest.WPF 一个支持中文用例的界面单元测试框架
腾讯云服务器OpenVPN Service
nginx个私有内网cdn

热门标签
.NET Core .NET Reactor ag-grid AI发布 api安全 ASP.NET Core C#DLL加密 C#播放声音 C#代码混淆 C#代码加密 ChromeDriver Codex DateTime DBeaver devexpress devTool DLL混淆 edge.js EF EFCore Electron element-ui el-form el-table excel FastReport FileStream FolderBrowerDialog FolderSelectDialog form提交 git gridcontrol gridview input javascript json字符串 JS转换对象JSON jwt JWT授权 linq log Math MCP mitmproxy MVC MySQL Navicat netstat nginx node_modules NSwag Nuget Nuget镜像 number PowerShell pyinstaller python pythoncom python爬虫 python抓包 pywin32 redis Requests-html RestSharp Selenium sql SQL Server Swagger to-cms Visual Studio VSCode vue VueRouter vue路由 VUE页面通讯 Webpack Windows Windows服务 winform wmi xlrd yaml YESCMS YESWEB开发框架 白象 表单提交 播放声音 打开URL 代码混淆 弹窗提醒 端口占用 对象转换 分布式 公共字典 机器码 进程排查 静态资源 开发指南 路由参数 密钥 配置教程 配置文件 权限 人工智能 任务 任务调度 日期间隔 日志 日志记录 省市区 授权验证 数据库 四舍五入 文案 文件读取 文件夹选择 文件目录选择 问题排查 行政区域数据 页面通讯 中间件 CSharp 事务锁 工单系统 并发控制 重复提交 CMS Markdig Markdown markdown-it marked 技术选型 VS Code 开发工具 源代码管理 版本控制 Docker PostgreSQL 时区 部署排查 CMS架构 EF Core 主题系统 二次开发 插件系统 容器 运维命令 镜像清理 Linux NAS 远程挂载 飞牛 fnOS S/4HANA SAP GUI SAP HANA SAP R/3 SAP入门 SAP版本 ERP SAP SAP MM 库存管理 物料管理 采购管理 入门教程 SAP S/4HANA SPRO 企业结构 采购组织 MM01 物料主数据 物料类型 BP分组 业务伙伴 供应商主数据 ME41 RFQ 库存物料 采购流程 ME51 消耗性物料 科目分配 采购申请 AC03 ML81N 外部服务 服务主数据 Business Partner SAP培训 ME51N MM模块 Lean Services MM-SRV 外部服务采购 PIR 供应来源 采购主数据 采购信息记录 ME31K 框架协议 计划协议 采购合同 ME01 供应来源确定 货源清单 MEQ1 供应源确定 配额安排 配额评分 MD04 MD21 MRP 计划文件 需求计划 批量程序 MD01N MD02 MRP Live MD05 MM 物料计划 优化采购 供应源 采购订单 ME2A 供应商确认 采购监控 Flexible Workflow 凭证释放 采购审批 释放策略 实地盘点 物料凭证 货物移动 MIGO 收货 移动类型 已撤回 供应商退货 货物发出 STO 库存转储 转移过账 生产订单 预留 GR/IR MIRO 供应商发票 物流发票校验 OMR2 税码 FI PP SD 实操教程 MRBR OMR6 发票差异 交货成本 后续借记 MI01 实物盘点 盘点差异 公司代码 工厂 组织结构 OMS2 主数据定制 自动科目确定 BP角色 CVI 伙伴确定 编号范围 凭证类型 字段选择 FBN1 OMBT OMC2 会计凭证 OMJJ BOM 委外加工 项目类别L MRKO 供应商寄售 特殊库存K MRKON PIPE Pipeline 特殊库存P ERS MRIS 发票计划 周期性结算 里程碑付款 变更追踪 版本管理 采购凭证 SFTP WebDAV 网盘 飞牛fnOS AMPL HERS MPN 中文教程 库存确定 可用性检查 缺件检查 Output Management 消息确定 输出确定 分割评估 库存计价 评估类别 评估类型 PB00 RM0000 条件技术 采购定价 MM-FI集成 OBYC 库存估价 文本类型 文本采用 EFB EVO MSV SU3 用户参数 发票校验 合同参照 履约保留款 特别总账 预付款 Fiori Launchpad SAP Fiori 应用导航 用户体验 LSMW LTMC Migration Cockpit 数据迁移 BRFplus OPD Output Control My Inbox 审批流程 灵活工作流 SAP PP 外部加工 SAP QM 检验批 质量信息记录 采购收货 SAP PM 维护BOM 维护订单 SAP SD SAP Service 端到端流程 MM模块培训 FI-MM集成 供应商管理 审批配置 FICO入门 SAP FICO 财务配置 供应商税务 预扣税 House Bank 银行对账 客户清账 应收账款 FI控制 验证与替代 印度 GST 税务配置 F110 FBZP EWM入门 SAP EWM 仓库管理 OX14 成本核算 物料评估 后勤配置 物料组 价值更新 数量更新 PP-PI 流程制造 生产计划 容差配置 SAP事务码 SAP基础 TCODE Basis 事务代码 MMNR 编号区间 采购实操 组织架构 OMSF SAP实操 FI配置
联系我们
联系电话:15090125178(微信同号)
电子邮箱:garson_zhang@163.com
站长微信二维码
微信二维码