天天看點

.NET Core 3 WPF MVVM架構 Prism系列之導航系統

本文将介紹如何在.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則每一次導航到該頁面都會執行個體化一次

我們用代碼來示範這三個方法:

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這種單獨顯示一個活動視圖,可以通過Region的Activate和Deactivate方法激活和失效視圖,像ItemsControl這種可以同時顯示多個活動視圖的,可以通過Region的Add和Remove方法控制增加活動視圖和失效視圖,而當視圖的KeepAlive為false,Region的Activate另外一個視圖時,則該視圖的執行個體則會去除出區域,為什麼我們不在區域管理器講解該接口呢?因為當導航的時候,同樣的是在觸發了Region的Activate和Deactivate,當有IRegionMemberLifetime接口時則會觸發Region的Add和Remove方法,這裡可以去看下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情況一樣,當KeepAlive為false時,通過斷點知道,重新導航回LoginMainContent頁面時不會觸發IsNavigationTarget方法,是以可以

知道判斷順序是:KeepAlive -->IsNavigationTarget

3.IConfirmNavigationRequest

Prism的導航系統還支援再導航前允許是否需要導航的互動需求,這裡我們在CreateAccount注冊完使用者後尋問是否需要導航回LoginMainContent頁面,代碼如下:

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接口的IsNavigationTarget,OnNavigatedFrom和OnNavigatedTo方法中IsNavigationTarget,OnNavigatedFrom和OnNavigatedTo中形參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();
    }
 }
           
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();
}

           
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源碼

WPF

繼續閱讀