(6/7).NET Core 3 WPF MVVMフレームワーク Prismシリーズのナビゲーションシステム

(6/7).NET Core 3 WPF MVVMフレームワーク Prismシリーズのナビゲーションシステム

.NET Core3環境でMVVMフレームワークPrismのリージョンベースのナビゲーションシステムを使用する方法

最終更新 2023/06/11 0:34
RyzenAdorer
読了目安 10 分
カテゴリ
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 を使用したリージョンベースのナビゲーションシステムについて説明します。

Prism のナビゲーションシステムの説明に入る前に、例を見てみましょう。以前のデモプロジェクトでログイン画面を作成しました。

ここで、最初は 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 メソッドには 3 つの仮引数があります。

  • 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

2 つのページ間でナビゲーションする際に、いくつかのロジックを処理する必要がよくあります。例えば、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 インスタンスを再利用、false の場合はナビゲート毎に新しいインスタンスを作成。

コードでこれらの 3 つのメソッドをデモします。

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 ページのデータが消えているのがわかります。これは、2 回目のナビゲーション時に 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 メソッドの仮引数 NavigationContext オブジェクトの NavigationParameters プロパティ
  • IConfirmNavigationRequest インターフェースの ConfirmNavigationRequest 仮引数 NavigationContext オブジェクトの NavigationParameters プロパティ
  • リージョンナビゲーションの INavigateAsync インターフェースの RequestNavigate メソッドの仮引数 navigationParameters
  • ナビゲーション履歴 IRegionNavigationJournal インターフェースの CurrentEntry プロパティの NavigationParameters 型の Parameters プロパティ(ナビゲーション履歴については後述)

ここでは、CreateAccount ページでユーザー登録後に、登録したユーザーをログイン ID として使用するかどうかを確認する例で、ナビゲーションパラメータの受け渡しをデモします。コードは以下のとおりです。

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 に依存しないためです。ただし、MVVM モードではより柔軟で、依存性注入をサポートし、リージョンマネージャーによってビューをより適切に管理でき、複雑なアプリケーションの要件に適応できるため、Prism のナビゲーションシステムを単独で使用することをお勧めします。WPF のナビゲーションシステムは依存性注入モードをサポートしておらず、Frame 要素に依存し、ナビゲーションプロセス中にビュー部分に強く依存しやすいという欠点があります。次の記事では、Prism のダイアログサービスについて説明します。

6. ソースコード

最後に、デモ全体のソースコードを添付します:PrismDemo ソースコード

さらに探索

関連読書

その他の記事