本文將介紹如何在.NET Core3環境下使用MVVM框架Prism基於區域Region的導航系統
在講解Prism導航系統之前,我們先來看看一個例子,我在之前的demo項目創建一個登錄界面:
我們看到這裡是不是一開始想象到使用WPF帶有的導航系統,通過Frame和Page進行頁面跳轉,然後通過導航日誌的GoBack和GoForward實現後退和前進,其實這是通過使用Prism的導航框架實現的,下面我們來看看如何在Prism的MVVM模式下實現該功能
一.區域導航#
我們在上一篇介紹了Prism的區域管理,而Prism的導航系統也是基於區域的,首先我們來看看如何在區域導航
1.註冊區域#
LoginWindow.xaml:
<code>Copy /<code>
2.註冊導航#
App.cs:
<code>Copy protected override void RegisterTypes(IContainerRegistry containerRegistry) { containerRegistry.Register(); containerRegistry.Register(); containerRegistry.Register(); //註冊全局命令 containerRegistry.RegisterSingleton(); containerRegistry.RegisterInstance(Container.Resolve()); //註冊導航 containerRegistry.RegisterForNavigation(); containerRegistry.RegisterForNavigation(); } /<code>
3.區域導航#
LoginWindowViewModel.cs:
<code>Copypublic 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; } } /<code>
LoginMainContentViewModel.cs:
<code>Copypublic 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; } } /<code>
效果如下:
這裡我們可以看到我們調用RegionMannager的RequestNavigate方法,其實這樣看不能很好的說明是基於區域的做法,如果將換成下面的寫法可能更好理解一點:
<code>Copy //在LoginContentRegion區域導航到LoginMainContent _regionManager.RequestNavigate(RegionNames.LoginContentRegion, "LoginMainContent"); /<code>
換成
<code>Copy //在LoginContentRegion區域導航到LoginMainContent IRegion region = _regionManager.Regions[RegionNames.LoginContentRegion]; region.RequestNavigate("LoginMainContent"); /<code>
其實RegionMannager的RequestNavigate源碼也是大概實現也是大概如此,就是去調Region的RequestNavigate的方法,而Region的導航是實現了一個INavigateAsync接口:
<code>Copypublic interface INavigateAsync { void RequestNavigate(Uri target, Action navigationCallback); void RequestNavigate(Uri target, Action navigationCallback, NavigationParameters navigationParameters); } /<code>
我們可以看到有RequestNavigate方法三個形參:
- target:表示將要導航的頁面Uri
- navigationCallback:導航後的回調方法
- navigationParameters:導航傳遞參數(下面會詳解)
那麼我們將上述加上回調方法:
<code>Copy //在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頁面失敗"); } } /<code>
效果如下:
二.View和ViewModel參與導航過程#
1.INavigationAware#
我們經常在兩個頁面之間導航需要處理一些邏輯,例如,LoginMainContent頁面導航到CreateAccount頁面時候,LoginMainContent退出頁面的時刻要保存頁面數據,導航到CreateAccount頁面的時刻處理邏輯(例如獲取從LoginMainContent頁面的信息),Prism的導航系統通過一個INavigationAware接口:
<code>Copy public interface INavigationAware : Object { Void OnNavigatedTo(NavigationContext navigationContext); Boolean IsNavigationTarget(NavigationContext navigationContext); Void OnNavigatedFrom(NavigationContext navigationContext); } /<code>
- OnNavigatedFrom:導航之前觸發,一般用於保存該頁面的數據
- OnNavigatedTo:導航後目的頁面觸發,一般用於初始化或者接受上頁面的傳遞參數
- IsNavigationTarget:True則重用該View實例,Flase則每一次導航到該頁面都會實例化一次
我們用代碼來演示這三個方法:
LoginMainContentViewModel.cs:
<code>Copypublic 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"); } } /<code>
CreateAccountViewModel.cs:
<code>Copypublic 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"); } } /<code>
效果如下:
修改IsNavigationTarget為false:
<code>Copypublic class LoginMainContentViewModel : BindableBase, INavigationAware { public bool IsNavigationTarget(NavigationContext navigationContext) { return false; } } public class CreateAccountViewModel : BindableBase,INavigationAware { public bool IsNavigationTarget(NavigationContext navigationContext) { return false; } } /<code>
效果如下:
我們會發現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:
<code>Copypublic 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"); } } /<code>
效果如下:
我們會發現跟沒實現IRegionMemberLifetime接口和IsNavigationTarget設置為false情況一樣,當KeepAlive為false時,通過斷點知道,重新導航回LoginMainContent頁面時不會觸發IsNavigationTarget方法,因此可以
知道判斷順序是:KeepAlive -->IsNavigationTarget
3.IConfirmNavigationRequest#
Prism的導航系統還支持再導航前允許是否需要導航的交互需求,這裡我們在CreateAccount註冊完用戶後尋問是否需要導航回LoginMainContent頁面,代碼如下:
CreateAccountViewModel.cs:
<code>Copypublic class CreateAccountViewModel : BindableBase, INavigationAware,IConfirmNavigationRequest { private DelegateCommand _loginMainContentCommand; public DelegateCommand LoginMainContentCommand => _loginMainContentCommand ?? (_loginMainContentCommand = new DelegateCommand(ExecuteLoginMainContentCommand)); private DelegateCommand _verityCommand; public DelegateCommand VerityCommand => _verityCommand ?? (_verityCommand = new DelegateCommand(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 continuationCallback) { var result = false; if (MessageBox.Show("是否需要導航到LoginMainContent頁面?", "Naviagte?",MessageBoxButton.YesNo) ==MessageBoxResult.Yes) { result = true; } continuationCallback(result); } } /<code>
效果如下:
三.導航期間傳遞參數#
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(修改代碼部分):
<code>Copyprivate 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 continuationCallback) { if (!string.IsNullOrEmpty(RegisteredLoginId) && this.IsUseRequest) { if (MessageBox.Show("是否需要用當前註冊的用戶登錄?", "Naviagte?", MessageBoxButton.YesNo) == MessageBoxResult.Yes) { navigationContext.Parameters.Add("loginId", RegisteredLoginId); } } continuationCallback(true); } /<code>
LoginMainContentViewModel.cs(修改代碼部分):
<code>Copypublic void OnNavigatedTo(NavigationContext navigationContext) { MessageBox.Show("從CreateAccount導航到LoginMainContent"); var loginId= navigationContext.Parameters["loginId"] as string; if (loginId!=null) { this.CurrentUser = new User() { LoginId=loginId}; } } /<code>
效果如下:
四.導航日誌#
Prism導航系統同樣的和WPF導航系統一樣,都支持導航日誌,Prism是通過IRegionNavigationJournal接口來提供區域導航日誌功能,
<code>Copy 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(); } /<code>
我們將在登錄界面接入導航日誌功能,代碼如下:
LoginMainContent.xaml(前進箭頭代碼部分):
<code>Copy /<code>
BoolToVisibilityConverter.cs:
<code>Copypublic 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(); } } /<code>
LoginMainContentViewModel.cs(修改代碼部分):
<code>CopyIRegionNavigationJournal _journal; private DelegateCommand _loginCommand; public DelegateCommand LoginCommand => _loginCommand ?? (_loginCommand = new DelegateCommand(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(); } /<code>
CreateAccountViewModel.cs(修改代碼部分):
<code>CopyIRegionNavigationJournal _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; } /<code>
效果如下:
選擇退出導航日誌#
如果不打算將頁面在導航過程中不加入導航日誌,例如LoginMainContent頁面,可以通過實現IJournalAware並從PersistInHistory()返回false
<code>Copy public class LoginMainContentViewModel : IJournalAware { public bool PersistInHistory() => false; } /<code>
五.小結:#
prism的導航系統可以跟wpf導航並行使用,這是prism官方文檔也支持的,因為prism的導航系統是基於區域的,不依賴於wpf,不過更推薦於單獨使用prism的導航系統,因為在MVVM模式下更靈活,支持依賴注入,通過區域管理器能夠更好的管理視圖View,更能適應複雜應用程序需求,wpf導航系統不支持依賴注入模式,也依賴於Frame元素,而且在導航過程中也是容易強依賴View部分,下一篇將會講解Prism的對話框服務
六.源碼#
最後,附上整個demo的源代碼:PrismDemo源碼
作者: RyzenAdorer
出處:https://www.cnblogs.com/ryzen/p/12703914.html
關鍵字: LoginMainContent 頁面 private