本文將介紹如何在.NET Core3環境下使用MVVM框架Prism基於區域Region的導航系統
在講解Prism導航系統之前,我們先來看看一個例子,我在之前的demo專案建立一個登入介面:
我們看到這裡是不是一開始想象到使用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;
}
}
效果如下:
這裡我們可以看到我們呼叫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頁面失敗");
}
}
效果如下:
二.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則每一次導航到該頁面都會例項化一次
我們用程式碼來演示這三個方法:
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.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
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);
}
}
效果如下:
三.導航期間傳遞引數
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};
}
}
效果如下:
四.導航日誌
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;
}
效果如下:
選擇退出導航日誌
如果不打算將頁面在導航過程中不加入導航日誌,例如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原始碼