(6/7).NET Core 3 WPF MVVM框架 Prism系列之導航系統

(6/7).NET Core 3 WPF MVVM框架 Prism系列之導航系統

如何在.NET Core3環境下使用MVVM框架Prism基於區域Region的導航系統

最後更新 2023/6/11 上午12:34
RyzenAdorer
預計閱讀 13 分鐘
分類
WPF
專題
WPF MVVM框架 Prism系列
標籤
.NET C# WPF Prism MVVM

本文來自轉載

原文作者:RyzenAdorer

原文標題:.NET Core 3 WPF MVVM 框架 Prism 系列之導覽系統

原文連結:https://www.cnblogs.com/ryzen/p/12703914.html

本文將介紹如何在.NET Core3 環境下使用 MVVM 框架 Prism 基於區域 Region 的導覽系統

在講解 Prism 導覽系統之前,我們先來看看一個例子,我在之前的 demo 專案建立一個登入介面:

我們看到這裡是不是一開始想像到使用 WPF 自帶的導覽系統,透過 Frame 和 Page 進行頁面跳轉,然後透過導覽日誌的 GoBack 和 GoForward 實現後退和前進,其實這是透過使用 Prism 的導覽框架實現的,下面我們來看看如何在 Prism 的 MVVM 模式下實現該功能

1. 區域導覽

我們在上一篇介紹了 Prism 的區域管理,而 Prism 的導覽系統也是基於區域的,首先我們來看看如何在區域導覽

1.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>

1.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>();
  }

1.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;
    }

 }

效果如下:

這裡我們可以看到我們呼叫 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頁面失敗");
     }
 }

效果如下:

2. View 和 ViewModel 參與導覽過程

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

 }

效果如下:

修改 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;
     }
 }

效果如下:

我們會發現 LoginMainContent 和 CreateAccount 頁面的資料不見了,這是因為第二次導覽到頁面的時候當 IsNavigationTarget 為 false 時,View 將會重新實例化,導致 ViewModel 也重新載入,因此所有資料都清空了

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

效果如下:

我們會發現跟沒實作 IRegionMemberLifetime 介面和 IsNavigationTarget 設定為 false 情況一樣,當 KeepAlive 為 false 時,透過斷點知道,重新導覽回 LoginMainContent 頁面時不會觸發 IsNavigationTarget 方法,因此可以知道判斷順序是:KeepAlive -->IsNavigationTarget

2.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);
      }
 }

效果如下:

3. 導覽期間傳遞參數

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

 }

效果如下:

4. 導覽日誌

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

效果如下:

4.1 選擇退出導覽日誌

如果不打算將頁面在導覽過程中不加入導覽日誌,例如 LoginMainContent 頁面,可以透過實作 IJournalAware 並從 PersistInHistory()傳回 false

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

5. 小結

prism 的導覽系統可以跟 wpf 導覽並行使用,這是 prism 官方文件也支援的,因為 prism 的導覽系統是基於區域的,不依賴於 wpf,不過更推薦於單獨使用 prism 的導覽系統,因為在 MVVM 模式下更靈活,支援依賴注入,透過區域管理器能夠更好的管理檢視 View,更能適應複雜應用程式需求,wpf 導覽系統不支援依賴注入模式,也依賴於 Frame 元素,而且在導覽過程中也是容易強依賴 View 部分,下一篇將會講解 Prism 的對話方塊服務

6. 原始碼

最後,附上整個 demo 的原始碼:PrismDemo 原始碼

繼續探索

延伸閱讀

更多文章