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

.NET Core 3 WPF MVVM框架 Prism系列之导航系统

程序员文章站 2022-06-15 11:46:32
本文将介绍如何在.NET Core3环境下使用MVVM框架Prism基于区域Region的导航系统 在讲解Prism导航系统之前,我们先来看看一个例子,我在之前的demo项目创建一个登录界面: 我们看到这里是不是一开始想象到使用WPF带有的导航系统,通过Frame和Page进行页面跳转,然后通过导航 ......

本文将介绍如何在.net core3环境下使用mvvm框架prism基于区域region的导航系统

在讲解prism导航系统之前,我们先来看看一个例子,我在之前的demo项目创建一个登录界面:

.NET Core 3 WPF MVVM框架 Prism系列之导航系统

我们看到这里是不是一开始想象到使用wpf带有的导航系统,通过frame和page进行页面跳转,然后通过导航日志的goback和goforward实现后退和前进,其实这是通过使用prism的导航框架实现的,下面我们来看看如何在prism的mvvm模式下实现该功能

一.区域导航

我们在上一篇介绍了prism的区域管理,而prism的导航系统也是基于区域的,首先我们来看看如何在区域导航

1.注册区域

loginwindow.xaml:

<window x:class="prismmetrosample.shell.views.login.loginwindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:prismmetrosample.shell.views.login"
        xmlns:region="clr-namespace:prismmetrosample.infrastructure.constants;assembly=prismmetrosample.infrastructure"
        mc:ignorable="d"
        xmlns:prism="http://prismlibrary.com/"
        xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
         height="600" width="400" prism:viewmodellocator.autowireviewmodel="true" resizemode="noresize" windowstartuplocation="centerscreen"
        icon="pack://application:,,,/prismmetrosample.infrastructure;component/assets/photos/home, homepage, menu.png" >
    <i:interaction.triggers>
        <i:eventtrigger eventname="loaded">
            <i:invokecommandaction command="{binding loginloadingcommand}"/>
        </i:eventtrigger>
    </i:interaction.triggers>
    <grid>
        <contentcontrol prism:regionmanager.regionname="{x:static region:regionnames.logincontentregion}" margin="5"/>
    </grid>
</window>

2.注册导航

app.cs:

  protected override void registertypes(icontainerregistry containerregistry)
  {
        containerregistry.register<imedicineserivce, medicineserivce>();
        containerregistry.register<ipatientservice, patientservice>();
        containerregistry.register<iuserservice, userservice>();

        //注册全局命令
        containerregistry.registersingleton<iapplicationcommands, applicationcommands>();
        containerregistry.registerinstance<iflyoutservice>(container.resolve<flyoutservice>());

        //注册导航
        containerregistry.registerfornavigation<loginmaincontent>();
        containerregistry.registerfornavigation<createaccount>();
  }

3.区域导航

loginwindowviewmodel.cs:

public class loginwindowviewmodel:bindablebase
{

    private readonly iregionmanager _regionmanager;
    private readonly iuserservice _userservice;
    private delegatecommand _loginloadingcommand;
    public delegatecommand loginloadingcommand =>
            _loginloadingcommand ?? (_loginloadingcommand = new delegatecommand(executeloginloadingcommand));

    void executeloginloadingcommand()
    {
        //在logincontentregion区域导航到loginmaincontent
        _regionmanager.requestnavigate(regionnames.logincontentregion, "loginmaincontent");

         global.allusers = _userservice.getallusers();
    }

    public loginwindowviewmodel(iregionmanager regionmanager, iuserservice userservice)
    {
          _regionmanager = regionmanager;
          _userservice = userservice;            
    }

}

loginmaincontentviewmodel.cs:

public class loginmaincontentviewmodel : bindablebase
{
    private readonly iregionmanager _regionmanager;

    private delegatecommand _createaccountcommand;
    public delegatecommand createaccountcommand =>
            _createaccountcommand ?? (_createaccountcommand = new delegatecommand(executecreateaccountcommand));

    //导航到createaccount
    void executecreateaccountcommand()
    {
         navigate("createaccount");
    }

    private void navigate(string navigatepath)
    {
         if (navigatepath != null)
              _regionmanager.requestnavigate(regionnames.logincontentregion, navigatepath);
        
    }


    public loginmaincontentviewmodel(iregionmanager regionmanager)
    {
         _regionmanager = regionmanager;
    }

 }

效果如下:

.NET Core 3 WPF MVVM框架 Prism系列之导航系统

这里我们可以看到我们调用regionmannager的requestnavigate方法,其实这样看不能很好的说明是基于区域的做法,如果将换成下面的写法可能更好理解一点:

   //在logincontentregion区域导航到loginmaincontent
  _regionmanager.requestnavigate(regionnames.logincontentregion, "loginmaincontent");

换成

 //在logincontentregion区域导航到loginmaincontent
 iregion region = _regionmanager.regions[regionnames.logincontentregion];
 region.requestnavigate("loginmaincontent");

其实regionmannager的requestnavigate源码也是大概实现也是大概如此,就是去调region的requestnavigate的方法,而region的导航是实现了一个inavigateasync接口:

public interface inavigateasync
{
   void requestnavigate(uri target, action<navigationresult> navigationcallback);
   void requestnavigate(uri target, action<navigationresult> navigationcallback, navigationparameters navigationparameters);
    
}   

我们可以看到有requestnavigate方法三个形参:

  • target:表示将要导航的页面uri
  • navigationcallback:导航后的回调方法
  • navigationparameters:导航传递参数(下面会详解)

那么我们将上述加上回调方法:

 //在logincontentregion区域导航到loginmaincontent
 iregion region = _regionmanager.regions[regionnames.logincontentregion];
 region.requestnavigate("loginmaincontent", navigationcompelted);

 private void navigationcompelted(navigationresult result)
 {
     if (result.result==true)
     {
         messagebox.show("导航到loginmaincontent页面成功");
     }
     else
     {
         messagebox.show("导航到loginmaincontent页面失败");
     }
 }

效果如下:

.NET Core 3 WPF MVVM框架 Prism系列之导航系统

二.view和viewmodel参与导航过程

1.inavigationaware

我们经常在两个页面之间导航需要处理一些逻辑,例如,loginmaincontent页面导航到createaccount页面时候,loginmaincontent退出页面的时刻要保存页面数据,导航到createaccount页面的时刻处理逻辑(例如获取从loginmaincontent页面的信息),prism的导航系统通过一个inavigationaware接口:

    public interface inavigationaware : object
    {
        void onnavigatedto(navigationcontext navigationcontext);

        boolean isnavigationtarget(navigationcontext navigationcontext);

        void onnavigatedfrom(navigationcontext navigationcontext);
    }
  • onnavigatedfrom:导航之前触发,一般用于保存该页面的数据
  • onnavigatedto:导航后目的页面触发,一般用于初始化或者接受上页面的传递参数
  • isnavigationtarget:true则重用该view实例,flase则每一次导航到该页面都会实例化一次

我们用代码来演示这三个方法:

loginmaincontentviewmodel.cs:

public class loginmaincontentviewmodel : bindablebase, inavigationaware
{
     private readonly iregionmanager _regionmanager;

     private delegatecommand _createaccountcommand;
     public delegatecommand createaccountcommand =>
            _createaccountcommand ?? (_createaccountcommand = new delegatecommand(executecreateaccountcommand));

     void executecreateaccountcommand()
     {
         navigate("createaccount");
     }

     private void navigate(string navigatepath)
     {
         if (navigatepath != null)
            _regionmanager.requestnavigate(regionnames.logincontentregion, navigatepath);
     }

     public loginmaincontentviewmodel(iregionmanager regionmanager)
     {
          _regionmanager = regionmanager;
     }

     public bool isnavigationtarget(navigationcontext navigationcontext)
     {            
          return true;
     }

     public void onnavigatedfrom(navigationcontext navigationcontext)
     {
          messagebox.show("退出了loginmaincontent");
     }

     public void onnavigatedto(navigationcontext navigationcontext)
     {
          messagebox.show("从createaccount导航到loginmaincontent");
     }
 }

createaccountviewmodel.cs:

public class createaccountviewmodel : bindablebase,inavigationaware
{
     private delegatecommand _loginmaincontentcommand;
     public delegatecommand loginmaincontentcommand =>
            _loginmaincontentcommand ?? (_loginmaincontentcommand = new delegatecommand(executeloginmaincontentcommand));

     void executeloginmaincontentcommand()
     {
         navigate("loginmaincontent");
     }

     public createaccountviewmodel(iregionmanager regionmanager)
     {
         _regionmanager = regionmanager;
     }

     private void navigate(string navigatepath)
     {
        if (navigatepath != null)
            _regionmanager.requestnavigate(regionnames.logincontentregion, navigatepath);
     }

     public bool isnavigationtarget(navigationcontext navigationcontext)
     {
         return true;
     }

     public void onnavigatedfrom(navigationcontext navigationcontext)
     {
         messagebox.show("退出了createaccount");
     }

     public void onnavigatedto(navigationcontext navigationcontext)
     {
         messagebox.show("从loginmaincontent导航到createaccount");
     }

 }

效果如下:

.NET Core 3 WPF MVVM框架 Prism系列之导航系统

修改isnavigationtarget为false:

public class loginmaincontentviewmodel : bindablebase, inavigationaware
{
     public bool isnavigationtarget(navigationcontext navigationcontext)
     {            
          return false;
     }
}

public class createaccountviewmodel : bindablebase,inavigationaware
{
     public bool isnavigationtarget(navigationcontext navigationcontext)
     {
         return false;
     }
 }

效果如下:

.NET Core 3 WPF MVVM框架 Prism系列之导航系统

我们会发现loginmaincontent和createaccount页面的数据不见了,这是因为第二次导航到页面的时候当isnavigationtarget为false时,view将会重新实例化,导致viewmodel也重新加载,因此所有数据都清空了

2.iregionmemberlifetime

同时,prism还可以通过iregionmemberlifetime接口的keepalive布尔属性控制区域的视图的生命周期,我们在上一篇关于区域管理器说到,当视图添加到区域时候,像contentcontrol这种单独显示一个活动视图,可以通过regionactivatedeactivate方法激活和失效视图,像itemscontrol这种可以同时显示多个活动视图的,可以通过regionaddremove方法控制增加活动视图和失效视图,而当视图的keepalivefalseregionactivate另外一个视图时,则该视图的实例则会去除出区域,为什么我们不在区域管理器讲解该接口呢?因为当导航的时候,同样的是在触发了regionactivatedeactivate,当有iregionmemberlifetime接口时则会触发regionaddremove方法,这里可以去看下prism的regionmemberlifetimebehavior源码

我们将loginmaincontentviewmodel实现iregionmemberlifetime接口,并且把keepalive设置为false,同样的将isnavigationtarget设置为true

loginmaincontentviewmodel.cs:

public class loginmaincontentviewmodel : bindablebase, inavigationaware,iregionmemberlifetime
{

     public bool keepalive => false;
     
     private readonly iregionmanager _regionmanager;

     private delegatecommand _createaccountcommand;
     public delegatecommand createaccountcommand =>
            _createaccountcommand ?? (_createaccountcommand = new delegatecommand(executecreateaccountcommand));

     void executecreateaccountcommand()
     {
         navigate("createaccount");
     }

     private void navigate(string navigatepath)
     {
         if (navigatepath != null)
            _regionmanager.requestnavigate(regionnames.logincontentregion, navigatepath);
     }

     public loginmaincontentviewmodel(iregionmanager regionmanager)
     {
          _regionmanager = regionmanager;
     }

     public bool isnavigationtarget(navigationcontext navigationcontext)
     {            
          return true;
     }

     public void onnavigatedfrom(navigationcontext navigationcontext)
     {
          messagebox.show("退出了loginmaincontent");
     }

     public void onnavigatedto(navigationcontext navigationcontext)
     {
          messagebox.show("从createaccount导航到loginmaincontent");
     }
 }

效果如下:

.NET Core 3 WPF MVVM框架 Prism系列之导航系统

我们会发现跟没实现iregionmemberlifetime接口和isnavigationtarget设置为false情况一样,当keepalivefalse时,通过断点知道,重新导航回loginmaincontent页面时不会触发isnavigationtarget方法,因此可以

知道判断顺序是:keepalive -->isnavigationtarget

3.iconfirmnavigationrequest

prism的导航系统还支持再导航前允许是否需要导航的交互需求,这里我们在createaccount注册完用户后寻问是否需要导航回loginmaincontent页面,代码如下:

createaccountviewmodel.cs:

public class createaccountviewmodel : bindablebase, inavigationaware,iconfirmnavigationrequest
{
     private delegatecommand _loginmaincontentcommand;
     public delegatecommand loginmaincontentcommand =>
            _loginmaincontentcommand ?? (_loginmaincontentcommand = new delegatecommand(executeloginmaincontentcommand));
    
     private delegatecommand<object> _veritycommand;
     public delegatecommand<object> veritycommand =>
            _veritycommand ?? (_veritycommand = new delegatecommand<object>(executeveritycommand));

     void executeloginmaincontentcommand()
     {
         navigate("loginmaincontent");
     }

     public createaccountviewmodel(iregionmanager regionmanager)
     {
         _regionmanager = regionmanager;
     }

     private void navigate(string navigatepath)
     {
        if (navigatepath != null)
            _regionmanager.requestnavigate(regionnames.logincontentregion, navigatepath);
     }

     public bool isnavigationtarget(navigationcontext navigationcontext)
     {
         return true;
     }

     public void onnavigatedfrom(navigationcontext navigationcontext)
     {
         messagebox.show("退出了createaccount");
     }

     public void onnavigatedto(navigationcontext navigationcontext)
     {
         messagebox.show("从loginmaincontent导航到createaccount");
     }
    
     //注册账号
     void executeveritycommand(object parameter)
     {
         if (!verityregister(parameter))
         {
                return;
         }
         messagebox.show("注册成功!");
         loginmaincontentcommand.execute();
     }
    
     //导航前询问
     public void confirmnavigationrequest(navigationcontext navigationcontext, action<bool> continuationcallback)
     {
         var result = false;
         if (messagebox.show("是否需要导航到loginmaincontent页面?", "naviagte?",messageboxbutton.yesno) ==messageboxresult.yes)
         {
             result = true;
         }
         continuationcallback(result);
      }
 }

效果如下:

.NET Core 3 WPF MVVM框架 Prism系列之导航系统

三.导航期间传递参数

prism提供navigationparameters类以帮助指定和检索导航参数,在导航期间,可以通过访问以下方法来传递导航参数:

  • inavigationaware接口的isnavigationtargetonnavigatedfromonnavigatedto方法中isnavigationtargetonnavigatedfromonnavigatedto中形参navigationcontext对象的navigationparameters属性
  • iconfirmnavigationrequest接口的confirmnavigationrequest形参navigationcontext对象的navigationparameters属性
  • 区域导航的inavigateasync接口的requestnavigate方法赋值给其形参navigationparameters
  • 导航日志iregionnavigationjournal接口currententry属性的navigationparameters类型的parameters属性(下面会介绍导航日志)

这里我们createaccount页面注册完用户后询问是否需要用当前注册用户来作为登录loginid,来演示传递导航参数,代码如下:

createaccountviewmodel.cs(修改代码部分):

private string _registeredloginid;
public string registeredloginid
{
    get { return _registeredloginid; }
    set { setproperty(ref _registeredloginid, value); }
}

public bool isuserequest { get; set; }

void executeveritycommand(object parameter)
{
    if (!verityregister(parameter))
    {
        return;
    }
    this.isuserequest = true;
    messagebox.show("注册成功!");
    loginmaincontentcommand.execute();
}   

public void confirmnavigationrequest(navigationcontext navigationcontext, action<bool> continuationcallback)
{
    if (!string.isnullorempty(registeredloginid) && this.isuserequest)
    {
         if (messagebox.show("是否需要用当前注册的用户登录?", "naviagte?", messageboxbutton.yesno) == messageboxresult.yes)
         {
              navigationcontext.parameters.add("loginid", registeredloginid);
         }
    }
    continuationcallback(true);
}

loginmaincontentviewmodel.cs(修改代码部分):

public void onnavigatedto(navigationcontext navigationcontext)
{
     messagebox.show("从createaccount导航到loginmaincontent");
            
     var loginid= navigationcontext.parameters["loginid"] as string;
     if (loginid!=null)
     {
         this.currentuser = new user() { loginid=loginid};
     }
            
 }

效果如下:

.NET Core 3 WPF MVVM框架 Prism系列之导航系统

四.导航日志

prism导航系统同样的和wpf导航系统一样,都支持导航日志,prism是通过iregionnavigationjournal接口来提供区域导航日志功能,

    public interface iregionnavigationjournal
    {
        bool cangoback { get; }

        bool cangoforward { get; }

        iregionnavigationjournalentry currententry {get;}

        inavigateasync navigationtarget { get; set; }

        void goback();

        void goforward();

        void recordnavigation(iregionnavigationjournalentry entry, bool persistinhistory);

        void clear();
    }

我们将在登录界面接入导航日志功能,代码如下:

loginmaincontent.xaml(前进箭头代码部分):

<textblock width="30" height="30" horizontalalignment="right" text="&#xe624;" fontweight="bold" fontfamily="pack://application:,,,/prismmetrosample.infrastructure;component/assets/fonts/#iconfont" fontsize="30" margin="10" visibility="{binding iscanexcute,converter={staticresource booltovisibilityconverter}}">
      <i:interaction.triggers>
           <i:eventtrigger eventname="mouseleftbuttondown">
                 <i:invokecommandaction command="{binding goforwardcommand}"/>
            </i:eventtrigger>
      </i:interaction.triggers>
      <textblock.style>
           <style targettype="textblock">
                <style.triggers>
                    <trigger property="ismouseover" value="true">
                          <setter property="background" value="#f9f9f9"/>
                    </trigger>
                 </style.triggers>
            </style>
      </textblock.style>
 </textblock>

booltovisibilityconverter.cs:

public class booltovisibilityconverter : ivalueconverter
{
    public object convert(object value, type targettype, object parameter, cultureinfo culture)
    {
          if (value==null)
          {
              return dependencyproperty.unsetvalue;
          }
          var iscanexcute = (bool)value;
          if (iscanexcute)
          {
              return visibility.visible;
          }
          else
          {
              return visibility.hidden;
          }
    }

    public object convertback(object value, type targettype, object parameter, cultureinfo culture)
    {
            throw new notimplementedexception();
    }
 }

loginmaincontentviewmodel.cs(修改代码部分):

iregionnavigationjournal _journal;

private delegatecommand<passwordbox> _logincommand;
public delegatecommand<passwordbox> logincommand =>
            _logincommand ?? (_logincommand = new delegatecommand<passwordbox>(executelogincommand, canexecutegoforwardcommand));

private delegatecommand _goforwardcommand;
public delegatecommand goforwardcommand =>
            _goforwardcommand ?? (_goforwardcommand = new delegatecommand(executegoforwardcommand));

private void executegoforwardcommand()
{
    _journal.goforward();
}

private bool canexecutegoforwardcommand(passwordbox passwordbox)
{
    this.iscanexcute=_journal != null && _journal.cangoforward;
    return true;
}

public void onnavigatedto(navigationcontext navigationcontext)
{
     //messagebox.show("从createaccount导航到loginmaincontent");
     _journal = navigationcontext.navigationservice.journal;

     var loginid= navigationcontext.parameters["loginid"] as string;
     if (loginid!=null)
     {
                this.currentuser = new user() { loginid=loginid};
     }
     logincommand.raisecanexecutechanged();
}

createaccountviewmodel.cs(修改代码部分):

iregionnavigationjournal _journal;

private delegatecommand _gobackcommand;
public delegatecommand gobackcommand =>
            _gobackcommand ?? (_gobackcommand = new delegatecommand(executegobackcommand));

void executegobackcommand()
{
     _journal.goback();
}

 public void onnavigatedto(navigationcontext navigationcontext)
 {
     //messagebox.show("从loginmaincontent导航到createaccount");
     _journal = navigationcontext.navigationservice.journal;
 }

效果如下:

.NET Core 3 WPF MVVM框架 Prism系列之导航系统

选择退出导航日志

如果不打算将页面在导航过程中不加入导航日志,例如loginmaincontent页面,可以通过实现ijournalaware并从persistinhistory()返回false

    public class loginmaincontentviewmodel : ijournalaware
    {
        public bool persistinhistory() => false;
    }   

五.小结:

prism的导航系统可以跟wpf导航并行使用,这是prism官方文档也支持的,因为prism的导航系统是基于区域的,不依赖于wpf,不过更推荐于单独使用prism的导航系统,因为在mvvm模式下更灵活,支持依赖注入,通过区域管理器能够更好的管理视图view,更能适应复杂应用程序需求,wpf导航系统不支持依赖注入模式,也依赖于frame元素,而且在导航过程中也是容易强依赖view部分,下一篇将会讲解prism的对话框服务

六.源码

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