この記事は転載から
著者:Ryzen Adorer
前の記事:. NET Core 3 WPF MVVMフレームワークPrismシリーズのナビゲーションシステム
原文へのリンク:https//www.cnblogs.com/ryzen/p/12703914.html
この記事では、. NET Core3環境でMVVMフレームワークPrismの地域ベースナビゲーションシステムを使用する方法について説明します。
Prismナビゲーションシステムについて説明する前に、以前のデモプロジェクトでログインインターフェイスを作成した例を見てみましょう。

最初はWPFに付属するナビゲーションシステムを使ってフレームとページを移動してからナビゲーションログの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. ナビゲーションプロセスにおけるビューと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はページに移動するたびにインスタンス化します。
以下の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ページのデータが欠落していることがわかります。これは、IsNavigationTargetがfalseになると、Viewが再インスタンス化され、ViewModelも再ロードされ、すべてのデータが空になるためです。
2.2. IRegionMemberLifetime
同时,Prism也可通通过IRegionMemberLifetimeインターフェイス的 KeepAlive Boolean属性制御区域的ビューのライフサイクル,我们在前一篇关关于区域管理器说,时ビューが区域に追加された时,像 ContentControl这种别表示一个活动ビュー,可通过Region 的 Activate 和 Deactivateメソッド活性化と無効化ビュー,像 ItemsControl这种可以同时表示多活动ビュー的,アクティブなビューの追加と無効なビューはRegionのAddとRemoveメソッドで制御できますが、ビューのKeepAliveがfalseで、RegionのActivateが別のビューの場合、ビューのインスタンスはRegionから削除されます。ナビゲーション時には、同じ地域のActivateとDeactivateがトリガーされるため、IRegionMemberLifetimeインターフェイスがある場合、RegionのAddとRemoveメソッドがトリガーされます。PrismのRegionMemberLifetimeBe haviorソースコードを参照してください。
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="" 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モードでより柔軟で、依存注入をサポートしています。Frame要素にも依存しており、ナビゲーションプロセス中にView 部分にも依存しやすいので、次の記事ではPrismのダイアログサービスについて説明します。
6. ソースコードソース
最后,附上整个 demo 的源代码:PrismDemo 源码