欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

.NET Core 3 WPF MVVM框架 Prism系列之区域管理器

程序员文章站 2022-04-27 18:37:34
本文将介绍如何在.NET Core3环境下使用MVVM框架Prism的使用区域管理器对于View的管理 一.区域管理器 我们在之前的Prism系列构建了一个标准式Prism项目,这篇文章将会讲解之前项目中用到的利用区域管理器更好的对我们的View进行管理,同样的我们来看看官方给出的模型图: 现在我们 ......

本文将介绍如何在.net core3环境下使用mvvm框架prism的使用区域管理器对于view的管理

一.区域管理器

我们在之前的prism系列构建了一个标准式prism项目,这篇文章将会讲解之前项目中用到的利用区域管理器更好的对我们的view进行管理,同样的我们来看看官方给出的模型图:

.NET Core 3 WPF MVVM框架 Prism系列之区域管理器

现在我们可以知道的是,大致一个区域管理器regionmannager对一个控件创建区域的要点:

  • 创建region的控件必须包含一个regionadapter适配器
  • region是依赖在具有regionadapter控件身上的

其实后来我去看了下官方的介绍和源码,默认regionadapter是有三个,且还支持自定义regionadapter,因此在官方的模型图之间我做了点补充:

.NET Core 3 WPF MVVM框架 Prism系列之区域管理器

二.区域创建与视图的注入

我们先来看看我们之前项目的区域的划分,以及如何创建区域并且把view注入到区域中:

.NET Core 3 WPF MVVM框架 Prism系列之区域管理器

我们把整个主窗体划分了四个区域:

  • showsearchpatientregion:注入了showsearchpatient视图
  • patientlistregion:注入了patientlist视图
  • flyoutregion:注入了patientdetail和searchmedicine视图
  • showsearchpatientregion:注入了showsearchpatient视图

在prism中,我们有两种方式去实现区域创建和视图注入:

  1. viewdiscovery
  2. viewinjection

1.viewdiscovery

我们截取其中patientlistregion的创建和视图注入的代码(更仔细的可以去观看demo源码):

mainwindow.xaml:

<contentcontrol grid.row="2" prism:regionmanager.regionname="patientlistregion" margin="10"/>

这里相当于在后台mainwindow.cs:

regionmanager.setregionname(contentcontrol, "patientlistregion");

patientmodule.cs:

 public class patientmodule : imodule
 {
    public void oninitialized(icontainerprovider containerprovider)
    {
         var regionmanager = containerprovider.resolve<iregionmanager>();
         //patientlist
         regionmanager.registerviewwithregion(regionnames.patientlistregion, typeof(patientlist));
         //patientdetail-flyout
         regionmanager.registerviewwithregion(regionnames.flyoutregion, typeof(patientdetail));
           
     }

    public void registertypes(icontainerregistry containerregistry)
    {
           
    }
 }

2.viewinjection

我们在mainwindow窗体的loaded事件中使用viewinjection方式注入视图patientlist

mainwindow.xaml:

  <i:interaction.triggers>
      <i:eventtrigger eventname="loaded">
          <i:invokecommandaction command="{binding loadingcommand}"/>
       /i:eventtrigger>
  </i:interaction.triggers>

mainwindowviewmodel.cs:

      
private iregionmanager _regionmanager;
private iregion _paientlistregion;        
private patientlist _patientlistview;

private delegatecommand _loadingcommand;
public delegatecommand loadingcommand =>
     _loadingcommand ?? (_loadingcommand = new delegatecommand(executeloadingcommand));

void executeloadingcommand()
{
     _regionmanager = commonservicelocator.servicelocator.current.getinstance<iregionmanager>();
     _paientlistregion = _regionmanager.regions[regionnames.patientlistregion];
     _patientlistview = commonservicelocator.servicelocator.current.getinstance<patientlist>();
     _paientlistregion.add(_patientlistview);

 }
      

我们可以明显的感觉到两种方式的不同,viewdiscovery方式是自动地实例化视图并且加载出来,而viewinjection方式则是可以手动控制注入视图和加载视图的时机(上述例子是通过loaded事件),官方对于两者的推荐使用场景如下:

viewdiscovery

  • 需要或要求自动加载视图
  • 视图的单个实例将加载到该区域中

viewinjection

  • 需要显式或编程控制何时创建和显示视图,或者您需要从区域中删除视图
  • 需要在区域中显示相同视图的多个实例,其中每个视图实例都绑定到不同的数据
  • 需要控制添加视图的区域的哪个实例
  • 应用程序使用导航api(后面会讲到)

三.激活与失效视图

activate和deactivate

首先我们需要控制patientlist和medicinemaincontent两个视图的激活情况,上代码:

mainwindow.xaml:

<stackpanel grid.row="1">
    <button  content="load medicinemodule" fontsize="25"  margin="5" command="{binding loadmedicinemodulecommand}"/>
     <uniformgrid margin="5">
         <button content="activepaientlist" margin="5" command="{binding activepaientlistcommand}"/>
         <button content="deactivepaientlist" margin="5" command="{binding deactivepaientlistcommand}"/>
         <button content="activemedicinelist" margin="5" command="{binding activemedicinelistcommand}"/>
         <button content="deactivemedicinelist" margin="5" command="{binding deactivemedicinelistcommand}"/>
     </uniformgrid>
</stackpanel>

<contentcontrol grid.row="2" prism:regionmanager.regionname="patientlistregion" margin="10"/>
<contentcontrol grid.row="3" prism:regionmanager.regionname="medicinemaincontentregion"/>

mainwindowviewmodel.cs:

  private iregionmanager _regionmanager;
  private iregion _paientlistregion;
  private iregion _medicinelistregion;
  private patientlist _patientlistview;
  private medicinemaincontent _medicinemaincontentview;

  private bool _iscanexcute = false;
  public bool iscanexcute
  {
     get { return _iscanexcute; }
     set { setproperty(ref _iscanexcute, value); }
  }

  private delegatecommand _loadingcommand;
  public delegatecommand loadingcommand =>
      _loadingcommand ?? (_loadingcommand = new delegatecommand(executeloadingcommand));

  private delegatecommand _activepaientlistcommand;
  public delegatecommand activepaientlistcommand =>
      _activepaientlistcommand ?? (_activepaientlistcommand = new delegatecommand(executeactivepaientlistcommand));

  private delegatecommand _deactivepaientlistcommand;
  public delegatecommand deactivepaientlistcommand =>
      _deactivepaientlistcommand ?? (_deactivepaientlistcommand = new delegatecommand(executedeactivepaientlistcommand));

   private delegatecommand _activemedicinelistcommand;
   public delegatecommand activemedicinelistcommand =>
      _activemedicinelistcommand ?? (_activemedicinelistcommand = new delegatecommand(executeactivemedicinelistcommand)
      .observescanexecute(() => iscanexcute));

   private delegatecommand _deactivemedicinelistcommand;
   public delegatecommand deactivemedicinelistcommand =>
       _deactivemedicinelistcommand ?? (_deactivemedicinelistcommand = new delegatecommand(executedeactivemedicinelistcommand)
      .observescanexecute(() => iscanexcute));

   private delegatecommand _loadmedicinemodulecommand;
   public delegatecommand loadmedicinemodulecommand =>
       _loadmedicinemodulecommand ?? (_loadmedicinemodulecommand = new delegatecommand(executeloadmedicinemodulecommand));

 /// <summary>
 /// 窗体加载事件
 /// </summary>
 void executeloadingcommand()
 {
      _regionmanager = commonservicelocator.servicelocator.current.getinstance<iregionmanager>();
      _paientlistregion = _regionmanager.regions[regionnames.patientlistregion];
      _patientlistview = commonservicelocator.servicelocator.current.getinstance<patientlist>();
      _paientlistregion.add(_patientlistview);
      _medicinelistregion = _regionmanager.regions[regionnames.medicinemaincontentregion];
 }

  /// <summary>
  /// 失效medicinemaincontent视图
  /// </summary>
  void executedeactivemedicinelistcommand()
  {
      _medicinelistregion.deactivate(_medicinemaincontentview);
  }

  /// <summary>
  /// 激活medicinemaincontent视图
  /// </summary>
  void executeactivemedicinelistcommand()
  {
      _medicinelistregion.activate(_medicinemaincontentview);
  }

  /// <summary>
  /// 失效patientlist视图
  /// </summary>
  void executedeactivepaientlistcommand()
  {
       _paientlistregion.deactivate(_patientlistview);
  }

  /// <summary>
  /// 激活patientlist视图
  /// </summary>
  void executeactivepaientlistcommand()
  {
       _paientlistregion.activate(_patientlistview);
  }
  
  /// <summary>
  /// 加载medicinemodule
  /// </summary>
  void executeloadmedicinemodulecommand()
  {
       _modulemanager.loadmodule("medicinemodule");
       _medicinemaincontentview = (medicinemaincontent)_medicinelistregion.views
            .where(t => t.gettype() == typeof(medicinemaincontent)).firstordefault();
       this.iscanexcute = true;
   }

效果如下:

.NET Core 3 WPF MVVM框架 Prism系列之区域管理器

监控视图激活状态

prism其中还支持监控视图的激活状态,是通过在view中继承iactiveaware来实现的,我们以监控其中medicinemaincontent视图的激活状态为例子:

medicinemaincontentviewmodel.cs:

 public class medicinemaincontentviewmodel : bindablebase,iactiveaware
 {
     public event eventhandler isactivechanged;

     bool _isactive;
     public bool isactive
     {
         get { return _isactive; }
         set
         {
             _isactive = value;
             if (_isactive)
             {
                 messagebox.show("视图被激活了");
             }
             else
             {
                 messagebox.show("视图失效了");
             }
             isactivechanged?.invoke(this, new eventargs());
          }
      }

  }

.NET Core 3 WPF MVVM框架 Prism系列之区域管理器

add和remove

上述例子用的是contentcontrol,我们再用一个itemscontrol的例子,代码如下:

mainwindow.xaml:

  <metro:metrowindow.rightwindowcommands>
      <metro:windowcommands x:name="rightwindowcommandsregion" />
  </metro:metrowindow.rightwindowcommands>

mainwindow.cs:

 public mainwindow()
 {
    initializecomponent();
    var regionmanager= servicelocator.current.getinstance<iregionmanager>();
    if (regionmanager != null)
    {
       setregionmanager(regionmanager, this.flyoutscontrolregion, regionnames.flyoutregion);
       //创建windowcommands控件区域
       setregionmanager(regionmanager, this.rightwindowcommandsregion, regionnames.showsearchpatientregion);
    }
 }

 void setregionmanager(iregionmanager regionmanager, dependencyobject regiontarget, string regionname)
 {
     regionmanager.setregionname(regiontarget, regionname);
     regionmanager.setregionmanager(regiontarget, regionmanager);
 }

showsearchpatient.xaml:

<stackpanel x:class="prismmetrosample.medicinemodule.views.showsearchpatient"
       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
       xmlns:prism="http://prismlibrary.com/"  
       xmlns:const="clr-namespace:prismmetrosample.infrastructure.constants;assembly=prismmetrosample.infrastructure"
       orientation="horizontal"    
       xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
       prism:viewmodellocator.autowireviewmodel="true">
   <i:interaction.triggers>
       <i:eventtrigger eventname="loaded">
           <i:invokecommandaction command="{binding showsearchloadingcommand}"/>
       </i:eventtrigger>
   </i:interaction.triggers>
   <checkbox ischecked="{binding isshow}"/>
   <button command="{binding applicationcommands.showcommand}" commandparameter="{x:static const:flyoutnames.searchmedicineflyout}">
       <stackpanel orientation="horizontal">
           <image height="20" source="pack://application:,,,/prismmetrosample.infrastructure;component/assets/photos/按钮.png"/>
           <textblock text="show" fontweight="bold" fontsize="15" verticalalignment="center"/>
       </stackpanel>
   </button>
</stackpanel>

showsearchpatientviewmodel.cs:

 private iapplicationcommands _applicationcommands;
 private readonly iregionmanager _regionmanager;
 private showsearchpatient _showsearchpatientview;
 private iregion _region;

 public iapplicationcommands applicationcommands
 {
      get { return _applicationcommands; }
      set { setproperty(ref _applicationcommands, value); }
 }

 private bool _isshow=true;
 public bool isshow
 {
      get { return _isshow=true; }
      set 
      { 
          setproperty(ref _isshow, value);
          if (_isshow)
          {
               activeshowsearchpatient();
          }
          else
          {
               deactiveshowsearchpaitent();
          }
      }
 }

 private delegatecommand _showsearchloadingcommand;
 public delegatecommand showsearchloadingcommand =>
         _showsearchloadingcommand ?? (_showsearchloadingcommand = new delegatecommand(executeshowsearchloadingcommand));

 void executeshowsearchloadingcommand()
 {
        _region = _regionmanager.regions[regionnames.showsearchpatientregion];
        _showsearchpatientview = (showsearchpatient)_region.views
            .where(t => t.gettype() == typeof(showsearchpatient)).firstordefault();
 }


  public showsearchpatientviewmodel(iapplicationcommands applicationcommands,iregionmanager regionmanager)
  {
        this.applicationcommands = applicationcommands;
        _regionmanager = regionmanager;
  }

  /// <summary>
  /// 激活视图
  /// </summary>
  private void activeshowsearchpatient()
  {
       if (!_region.activeviews.contains(_showsearchpatientview))
       {
           _region.add(_showsearchpatientview);
       }         
  }
   
  /// <summary>
  /// 失效视图
  /// </summary>
   private async void deactiveshowsearchpaitent()
   {
        _region.remove(_showsearchpatientview);
        await task.delay(2000);
        isshow = true;
   }

效果如下:

.NET Core 3 WPF MVVM框架 Prism系列之区域管理器

这里的windowcommands 的继承链为:windowcommands <-- toolbar <-- headereditemscontrol <--itemscontrol,因此由于prism默认的适配器有itemscontrolregionadapter,因此其子类也继承了其行为

这里重点归纳一下:

  • 当进行模块化时,加载完模块才会去注入视图到区域(可参考medicinemodule视图加载顺序)
  • contentcontrol控件由于content只能显示一个,在其区域中可以通过activate和deactivate方法来控制显示哪个视图,其行为是由contentcontrolregionadapter适配器控制
  • itemscontrol控件及其子控件由于显示一个集合视图,默认全部集合视图是激活的,这时候不能通过activate和deactivate方式来控制(会报错),通过add和remove来控制要显示哪些视图,其行为是由itemscontrolregionadapter适配器控制
  • 这里没讲到selector控件,因为也是继承自itemscontrol,因此其selectorregionadapter适配器和itemscontrolregionadapter适配器异曲同工
  • 可以通过继承iactiveaware接口来监控视图激活状态

四.自定义区域适配器

我们在介绍整个区域管理器模型图中说过,prism有三个默认的区域适配器:itemscontrolregionadapter,contentcontrolregionadapter,selectorregionadapter,且支持自定义区域适配器,现在我们来自定义一下适配器

1.创建自定义适配器

新建类uniformgridregionadapter.cs:

public class uniformgridregionadapter : regionadapterbase<uniformgrid>
{
    public uniformgridregionadapter(iregionbehaviorfactory regionbehaviorfactory) : base(regionbehaviorfactory)
    {

    }

    protected override void adapt(iregion region, uniformgrid regiontarget)
    {
        region.views.collectionchanged += (s, e) =>
        {
          if (e.action==system.collections.specialized.notifycollectionchangedaction.add)
          {
              foreach (frameworkelement element in e.newitems)
              {
                   regiontarget.children.add(element);
              }
          }
        };
    }

    protected override iregion createregion()
    {
        return new allactiveregion();
    }
 }

2.注册映射

app.cs:

protected override void configureregionadaptermappings(regionadaptermappings regionadaptermappings)
{
    base.configureregionadaptermappings(regionadaptermappings);
    //为uniformgrid控件注册适配器映射
    regionadaptermappings.registermapping(typeof(uniformgrid),container.resolve<uniformgridregionadapter>());
}

3.为控件创建区域

mainwindow.xaml:

    <uniformgrid margin="5" prism:regionmanager.regionname="uniformcontentregion" columns="2">
        <button content="activepaientlist" margin="5" command="{binding activepaientlistcommand}"/>
        <button content="deactivepaientlist" margin="5" command="{binding deactivepaientlistcommand}"/>
        <button content="activemedicinelist" margin="5" command="{binding activemedicinelistcommand}"/>
        <button content="deactivemedicinelist" margin="5" command="{binding deactivemedicinelistcommand}"/>
     </uniformgrid>

4.为区域注入视图

这里用的是viewinjection方式:

mainwindowviewmodel.cs

  void executeloadingcommand()
  {
         _regionmanager = commonservicelocator.servicelocator.current.getinstance<iregionmanager>();

         var uniformcontentregion = _regionmanager.regions["uniformcontentregion"];
         var regionadapterview1 = commonservicelocator.servicelocator.current.getinstance<regionadapterview1>();
         uniformcontentregion.add(regionadapterview1);
         var regionadapterview2 = commonservicelocator.servicelocator.current.getinstance<regionadapterview2>();
         uniformcontentregion.add(regionadapterview2); 
  }

效果如图:

.NET Core 3 WPF MVVM框架 Prism系列之区域管理器

我们可以看到我们为uniformgrid创建区域适配器,并且注册后,也能够为uniformgrid控件创建区域,并且注入视图显示,如果没有该区域适配器,则是会报错,下一篇我们将会讲解基于区域region的prism导航系统。

五.源码

 最后,附上整个demo的源代码:prismdemo源码