百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

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

ccwgpt 2025-04-06 14:19 14 浏览 0 评论

本文将介绍如何在.NET Core3环境下使用MVVM框架Prism基于区域Region的导航系统

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

我们看到这里是不是一开始想象到使用WPF带有的导航系统,通过Frame和Page进行页面跳转,然后通过导航日志的GoBack和GoForward实现后退和前进,其实这是通过使用Prism的导航框架实现的,下面我们来看看如何在Prism的MVVM模式下实现该功能

一.区域导航#

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

1.注册区域#

LoginWindow.xaml:

Copy
    
        
            
        
    
    
        
    

2.注册导航#

App.cs:

Copy  protected override void RegisterTypes(IContainerRegistry containerRegistry)
  {
        containerRegistry.Register();
        containerRegistry.Register();
        containerRegistry.Register();

        //注册全局命令
        containerRegistry.RegisterSingleton();
        containerRegistry.RegisterInstance(Container.Resolve());

        //注册导航
        containerRegistry.RegisterForNavigation();
        containerRegistry.RegisterForNavigation();
  }

3.区域导航#

LoginWindowViewModel.cs:

Copypublic 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:

Copypublic 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;
    }

 }

效果如下:

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

Copy   //在LoginContentRegion区域导航到LoginMainContent
  _regionManager.RequestNavigate(RegionNames.LoginContentRegion, "LoginMainContent");

换成

Copy //在LoginContentRegion区域导航到LoginMainContent
 IRegion region = _regionManager.Regions[RegionNames.LoginContentRegion];
 region.RequestNavigate("LoginMainContent");

其实RegionMannager的RequestNavigate源码也是大概实现也是大概如此,就是去调Region的RequestNavigate的方法,而Region的导航是实现了一个INavigateAsync接口:

Copypublic interface INavigateAsync
{
   void RequestNavigate(Uri target, Action navigationCallback);
   void RequestNavigate(Uri target, Action navigationCallback, NavigationParameters navigationParameters);
    
}   

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

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

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

Copy //在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页面失败");
     }
 }

效果如下:

二.View和ViewModel参与导航过程#

1.INavigationAware#

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

Copy    public interface INavigationAware : Object
    {
        Void OnNavigatedTo(NavigationContext navigationContext);

        Boolean IsNavigationTarget(NavigationContext navigationContext);

        Void OnNavigatedFrom(NavigationContext navigationContext);
    }
  • OnNavigatedFrom:导航之前触发,一般用于保存该页面的数据
  • OnNavigatedTo:导航后目的页面触发,一般用于初始化或者接受上页面的传递参数
  • IsNavigationTarget:True则重用该View实例,Flase则每一次导航到该页面都会实例化一次

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

LoginMainContentViewModel.cs:

Copypublic 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:

Copypublic 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");
     }

 }

效果如下:

修改IsNavigationTarget为false:

Copypublic class LoginMainContentViewModel : BindableBase, INavigationAware
{
     public bool IsNavigationTarget(NavigationContext navigationContext)
     {            
          return false;
     }
}

public class CreateAccountViewModel : BindableBase,INavigationAware
{
     public bool IsNavigationTarget(NavigationContext navigationContext)
     {
         return false;
     }
 }

效果如下:

我们会发现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:

Copypublic 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");
     }
 }

效果如下:

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

知道判断顺序是:KeepAlive -->IsNavigationTarget

3.IConfirmNavigationRequest#

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

CreateAccountViewModel.cs:

Copypublic 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 continuationCallback)
     {
         var result = false;
         if (MessageBox.Show("是否需要导航到LoginMainContent页面?", "Naviagte?",MessageBoxButton.YesNo) ==MessageBoxResult.Yes)
         {
             result = true;
         }
         continuationCallback(result);
      }
 }

效果如下:

三.导航期间传递参数#

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

  • INavigationAware接口的IsNavigationTargetOnNavigatedFromOnNavigatedTo方法中IsNavigationTargetOnNavigatedFromOnNavigatedTo中形参NavigationContext对象的NavigationParameters属性
  • IConfirmNavigationRequest接口的ConfirmNavigationRequest形参NavigationContext对象的NavigationParameters属性
  • 区域导航的INavigateAsync接口的RequestNavigate方法赋值给其形参navigationParameters
  • 导航日志IRegionNavigationJournal接口CurrentEntry属性的NavigationParameters类型的Parameters属性(下面会介绍导航日志)

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

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

Copyprivate 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 continuationCallback)
{
    if (!string.IsNullOrEmpty(RegisteredLoginId) && this.IsUseRequest)
    {
         if (MessageBox.Show("是否需要用当前注册的用户登录?", "Naviagte?", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
         {
              navigationContext.Parameters.Add("loginId", RegisteredLoginId);
         }
    }
    continuationCallback(true);
}


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

Copypublic void OnNavigatedTo(NavigationContext navigationContext)
{
     MessageBox.Show("从CreateAccount导航到LoginMainContent");
            
     var loginId= navigationContext.Parameters["loginId"] as string;
     if (loginId!=null)
     {
         this.CurrentUser = new User() { LoginId=loginId};
     }
            
 }

效果如下:

四.导航日志#

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

Copy    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(前进箭头代码部分):

Copy
      
           
                 
            
      
      
           
      
 

BoolToVisibilityConverter.cs:

Copypublic 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(修改代码部分):

CopyIRegionNavigationJournal _journal;

private DelegateCommand _loginCommand;
public DelegateCommand LoginCommand =>
            _loginCommand ?? (_loginCommand = new DelegateCommand(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(修改代码部分):

CopyIRegionNavigationJournal _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;
 }

效果如下:

选择退出导航日志#

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

Copy    public class LoginMainContentViewModel : IJournalAware
    {
        public bool PersistInHistory() => false;
    }   

五.小结:#

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

六.源码#

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


作者: RyzenAdorer

出处:
https://www.cnblogs.com/ryzen/p/12703914.html

相关推荐

迈向群体智能 | 智源发布首个跨本体具身大小脑协作框架

允中发自凹非寺量子位|公众号QbitAI3月29日,智源研究院在2025中关村论坛“未来人工智能先锋论坛”上发布首个跨本体具身大小脑协作框架RoboOS与开源具身大脑RoboBrain,可实...

大模型对接微信个人号,极空间部署AstrBot机器人,万事不求百度

「亲爱的粉丝朋友们好啊!今天熊猫又来介绍好玩有趣的Docker项目了,喜欢的记得点个关注哦!」引言前两天熊猫发过一篇关于如何在极空间部署AstrBot并对接QQ消息平台的文章,不过其实QQ现在已经很少...

Seata,让分布式事务不再是难题!实战分享带你领略Seata的魅力!

终身学习、乐于分享、共同成长!前言Seata是一款开源的分布式事务解决方案,致力于提供高性能和简单易用的分布式事务服务。Seata将为用户提供了AT、TCC、SAGA和XA事务模式,为用户打造一站式的...

常见分布式事务解决方案(分布式事务解决的问题)

1.两阶段提交(2PC)原理:分为准备阶段(协调者询问参与者是否可提交)和提交阶段(协调者根据参与者反馈决定提交或回滚)。优点:强一致性,适用于数据库层(如XA协议)。缺点:同步阻塞:所有参与者阻塞...

分布式事务:从崩溃到高可用,程序员必须掌握的实战方案!

“支付成功,但订单状态未更新!”、“库存扣减后,交易却回滚了!”——如果你在分布式系统中踩过这些“天坑”,这篇文章就是你的救命稻草!本文将手把手拆解分布式事务的核心痛点和6大主流解决方案,用代码实战+...

谈谈对分布式事务的一点理解和解决方案

分布式事务首先,做系统拆分的时候几乎都会遇到分布式事务的问题,一个仿真的案例如下:项目初期,由于用户体量不大,订单模块和钱包模块共库共应用(大war包时代),模块调用可以简化为本地事务操作,这样做只要...

一篇教你通过Seata解决分布式事务问题

1 Seata介绍Seata是由阿里中间件团队发起的开源分布式事务框架项目,依赖支持本地ACID事务的关系型数据库,可以高效并且对业务0侵入的方式解决微服务场景下面临的分布式事务问题,目前提供AT...

Seata分布式事务详解(原理流程及4种模式)

Seata分布式事务是SpringCloudAlibaba的核心组件,也是构建分布式的基石,下面我就全面来详解Seata@mikechen本篇已收于mikechen原创超30万字《阿里架构师进阶专题合...

分布式事务最终一致性解决方案有哪些?MQ、TCC、saga如何实现?

JTA方案适用于单体架构多数据源时实现分布式事务,但对于微服务间的分布式事务就无能为力了,我们需要使用其他的方案实现分布式事务。1、本地消息表本地消息表的核心思想是将分布式事务拆分成本地事务进行处理...

彻底掌握分布式事务2PC、3PC模型(分布式事务视频教程)

原文:https://mp.weixin.qq.com/s/_zhntxv07GEz9ktAKuj70Q作者:马龙台工作中使用最多的是本地事务,但是在对单一项目拆分为SOA、微服务之后,就会牵扯出分...

Seata分布式事务框架关于Annotation的SAGA模式分析

SAGAAnnotation是ApacheSeata版本2.3.0中引入的功能,它提供了一种使用Java注解而不是传统的JSON配置或编程API来实现SAGA事务模式的声明...

分布式事务,原理简单,写起来全是坑

今天我们就一起来看下另一种模式,XA模式!其实我觉得seata中的四种不同的分布式事务模式,学完AT、TCC以及XA就够了,Saga不好玩,而且长事务本身就有很多问题,也不推荐使用。S...

内存空间节约利器redis的bitmap(位图)应用场景有哪些你知道吗

在前面我们分享过一次Redis常用数据结构和使用场景,文章对Redis基本使用做了一个简单的API说明,但是对于其中String类型中的bitmap(位图)我们需要重点说明一下,因为他的作用真的不容忽...

分布式事务原理详解(图文全面总结)

分布式事务是非常核心的分布式系统,也是大厂经常考察对象,下面我就重点详解分布式事务及原理实现@mikechen本文作者:陈睿|mikechen文章来源:mikechen.cc分布式事务分布式事务指的是...

大家平时天天说的分布式系统到底是什么东西?

目录从单块系统说起团队越来越大,业务越来越复杂分布式出现:庞大系统分而治之分布式系统所带来的技术问题一句话总结:什么是分布式系统设计和开发经验补充说明:中间件系统及大数据系统前言现在有很多Java技术...

取消回复欢迎 发表评论: