本文將介紹如何在.NET Core3環境下使用MVVM框架Prism基於區域Region的導航系統git
在講解Prism導航系統以前,咱們先來看看一個例子,我在以前的demo項目建立一個登陸界面:github
咱們看到這裏是否是一開始想象到使用WPF帶有的導航系統,經過Frame和Page進行頁面跳轉,而後經過導航日誌的GoBack和GoForward實現後退和前進,其實這是經過使用Prism的導航框架實現的,下面咱們來看看如何在Prism的MVVM模式下實現該功能express
咱們在上一篇介紹了Prism的區域管理,而Prism的導航系統也是基於區域的,首先咱們來看看如何在區域導航c#
LoginWindow.xaml:app
<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>
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>(); }
LoginWindowViewModel.cs:ide
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:this
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; } }
效果以下:spa
這裏咱們能夠看到咱們調用RegionMannager的RequestNavigate方法,其實這樣看不能很好的說明是基於區域的作法,若是將換成下面的寫法可能更好理解一點:3d
//在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方法三個形參:
那麼咱們將上述加上回調方法:
//在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頁面失敗"); } }
效果以下:
咱們常常在兩個頁面之間導航須要處理一些邏輯,例如,LoginMainContent頁面導航到CreateAccount頁面時候,LoginMainContent退出頁面的時刻要保存頁面數據,導航到CreateAccount頁面的時刻處理邏輯(例如獲取從LoginMainContent頁面的信息),Prism的導航系統經過一個INavigationAware接口:
public interface INavigationAware : Object { Void OnNavigatedTo(NavigationContext navigationContext); Boolean IsNavigationTarget(NavigationContext navigationContext); Void OnNavigatedFrom(NavigationContext navigationContext); }
咱們用代碼來演示這三個方法:
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也從新加載,所以全部數據都清空了
同時,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
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類以幫助指定和檢索導航參數,在導航期間,能夠經過訪問如下方法來傳遞導航參數:
這裏咱們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源碼