本文來自轉載
原文作者: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="" 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 源码