您当前的位置: 首页 >> 生活 > >> 内容页

Prism进入视图时导航的三种方式

2023-06-21 15:09:13 来源:博客园
Prism导航

新建视图UserControl及其ViewModel,被跳转的视图的VM需要实现INavigationAware


(资料图)

App.xaml.cs中注册视图及其ViewModel

// App.xaml.cscontainerRegistry.RegisterForNavigation();
在需要放置导航内容处声明ContentControlregion占位:
                                                    
RegionPrism内部的一个数据结构,它的Name属性是此处在XAML中声明的RegionName(详见下节)。在需要进行导航行为的ViewModel处注入并使用,如:
// ViewModel        public DelegateCommand NavigateCommand { get; private set; }        public MainWindowViewModel(IRegionManager regionManager)        {            _regionManager = regionManager;            NavigateCommand = new DelegateCommand(Navigate);        }        private void Navigate(string navigatePath)        {            if (navigatePath != null)                _regionManager.RequestNavigate("ContentRegion", navigatePath);        }
RegionManager

Region对应的是在XAML中声明的 ContentControl的附加属性 prism:RegionManager.RegionName

RegionManager管理着所有 Region对象,这些 Region对象被装到 RegionCollection中的列表属性

RegionManager中的3个方法

UpdateRegionsPrismApplicationBase#Initialize中被调用,它会根据在XAML中声明的RegionName创建 Region对象RequestNavigate在需要导航时调用,调用它时会根据 regionName 去 regionCollection 中找到对应的 Region对象,并通过集合 ActiveViews找到满足条件的 View 实例从而进行 ContentControl内容的切换可以主动调用 RegisterViewWithRegion进行 Region和视图的注册在进入视图时导航

由于 View 和 ViewModel 的初始化 MvvmHelpers.AutowireViewModel(shell);先于 Region的初始化RegionManager.UpdateRegions();,因此在View和ViewModel初始化时找不到相应的 Region对象。

// PrismApplicationBase.csprotected virtual void Initialize(){    // ...    if (shell != null)    {        MvvmHelpers.AutowireViewModel(shell);        RegionManager.SetRegionManager(shell, _containerExtension.Resolve());        RegionManager.UpdateRegions();        InitializeShell(shell);    }    // ...

在窗口初始化时,Initilized事件发生时数据绑定未完成;Loaded事件发生时数据绑定已经完成。

因此,可以手动注册 Region;也可以在数据绑定结束之后访问 Region

方法1 Loaded事件

private void Window_Loaded(object sender, RoutedEventArgs e){    regionManager.RequestNavigate("ContentRegion", "ViewA");}

方法2 手动注册 Region

// App.xaml.csprotected override void Initialize(){    base.Initialize();    var regionManager = Container.Resolve();    regionManager.RegisterViewWithRegion("ContentRegion", typeof(ViewA));}// ViewModelpublic MainWindowViewModel(IRegionManager regionManager){    regionManager.RequestNavigate("ContentRegion", "ViewA");}

方法3 Dispatcher

Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>{    regionManager.RequestNavigate("ContentRegion", "ViewA");}));
引用Prism - Region navigationlearn.microsoft - Object lifetime events (WPF .NET)
关键词:
分享到:

Copyright ©  2015-2022 每日时尚网版权所有  备案号:浙ICP备2022016517号-15   联系邮箱:5 146 761 13 @qq.com