IT评测·应用市场-qidao123.com

标题: Prism进入视图时导航的三种方式 [打印本页]

作者: 三尺非寒    时间: 2023-6-21 13:51
标题: Prism进入视图时导航的三种方式
Prism导航

  1. // App.xaml.cs
  2. containerRegistry.RegisterForNavigation<IndexView, IndexViewModel>();
复制代码
  1.     <DockPanel LastChildFill="True">
  2.         <StackPanel Orientation="Horizontal" DockPanel.Dock="Top" Margin="5" >
  3.             <Button Command="{Binding NavigateCommand}" CommandParameter="ViewA" Margin="5">Navigate to View A</Button>
  4.             <Button Command="{Binding NavigateCommand}" CommandParameter="ViewB" Margin="5">Navigate to View B</Button>
  5.         </StackPanel>
  6.         <ContentControl prism:RegionManager.RegionName
  7.             ="{x:Static ext:PrismManager.MainViewRegionName}" />
  8.     </DockPanel>
复制代码
  1. // ViewModel
  2.         public DelegateCommand<string> NavigateCommand { get; private set; }
  3.         public MainWindowViewModel(IRegionManager regionManager)
  4.         {
  5.             _regionManager = regionManager;
  6.             NavigateCommand = new DelegateCommand<string>(Navigate);
  7.         }
  8.         private void Navigate(string navigatePath)
  9.         {
  10.             if (navigatePath != null)
  11.                 _regionManager.RequestNavigate("ContentRegion", navigatePath);
  12.         }
复制代码
RegionManager


在进入视图时导航

由于 View 和 ViewModel 的初始化 MvvmHelpers.AutowireViewModel(shell); 先于 Region 的初始化RegionManager.UpdateRegions();,因此在View和ViewModel初始化时找不到相应的 Region 对象。
  1. // PrismApplicationBase.cs
  2. protected virtual void Initialize()
  3. {
  4.     // ...
  5.     if (shell != null)
  6.     {
  7.         MvvmHelpers.AutowireViewModel(shell);
  8.         RegionManager.SetRegionManager(shell, _containerExtension.Resolve<IRegionManager>());
  9.         RegionManager.UpdateRegions();
  10.         InitializeShell(shell);
  11.     }
  12.     // ...
复制代码
在窗口初始化时,Initilized 事件发生时数据绑定未完成;Loaded 事件发生时数据绑定已经完成。
因此,可以手动注册 Region;也可以在数据绑定结束之后访问 Region。
方法1 Loaded事件
  1. private void Window_Loaded(object sender, RoutedEventArgs e)
  2. {
  3.     regionManager.RequestNavigate("ContentRegion", "ViewA");
  4. }
复制代码
方法2 手动注册 Region
  1. // App.xaml.cs
  2. protected override void Initialize()
  3. {
  4.     base.Initialize();
  5.     var regionManager = Container.Resolve<IRegionManager>();
  6.     regionManager.RegisterViewWithRegion("ContentRegion", typeof(ViewA));
  7. }
  8. // ViewModel
  9. public MainWindowViewModel(IRegionManager regionManager)
  10. {
  11.     regionManager.RequestNavigate("ContentRegion", "ViewA");
  12. }
复制代码
方法3 Dispatcher
  1. Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
  2. {
  3.     regionManager.RequestNavigate("ContentRegion", "ViewA");
  4. }));
复制代码
引用


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!




欢迎光临 IT评测·应用市场-qidao123.com (https://dis.qidao123.com/) Powered by Discuz! X3.4