使用 Prism 在 PCL 中导航

Navigating in PCL using Prism

我正在使用 prism PCL 构建一个 UWP 应用程序。

PCL 包含 ViewModels

UWP 包含视图

我的问题是我无法在 PCL 中使用 INavigationService,所以我无法真正导航到其他页面。

这是我的代码:

MainPage.xaml(在 UWP 项目中):

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

        <SplitView x:Name="RootSplitView"
                   DisplayMode="Overlay"
                   IsTabStop="False">
            <SplitView.Pane>
                <StackPanel Margin="0,50,0,0">
                    <Button Content="Second" Command="{x:Bind ViewModel.SecondPageCommand}"  />
                    <Button Content="Third" />
                </StackPanel>
            </SplitView.Pane>

            <!-- OnNavigatingToPage we synchronize the selected item in the nav menu with the current page.
                 OnNavigatedToPage we move keyboard focus to the first item on the page after it's loaded and update the Back button. -->
            <Frame x:Name="FrameContent" />
        </SplitView>

        <ToggleButton x:Name="TogglePaneButton"
                      TabIndex="1"                      
                      IsChecked="{Binding IsPaneOpen, ElementName=RootSplitView, Mode=TwoWay}"
                      ToolTipService.ToolTip="Menu"
                      Style="{StaticResource SplitViewTogglePaneButtonStyle}"
                      />
    </Grid>

ViewModel(在PCL):

 public class NavigationRootViewModel : BindableBase
    {
        public ICommand SecondPageCommand { get; set; }
        public NavigationRootViewModel()
        {
            SecondPageCommand = DelegateCommand.FromAsyncHandler(ExecuteMethod);
        }

        private Task ExecuteMethod()
        {
            return Task.FromResult(0);
        }
    }

我希望在构造函数中注入 INavigationService 但它不是 Prism.Core dll 的一部分。

那么正确的做法是什么呢?甚至可以使用 Prism 在 PCL 中导航吗?在 MvvmCross 中它是...

我在我们的项目中使用了棱镜导航,如下。

var regionManager = container.Resolve<IRegionManager>();
if (screenName == SpEnums.ViewName.LuminationView.ToString())
{
     regionManager.RequestNavigate(Enums.Regions.MainRegion.ToString(),
     SpEnums.ViewName.LuminationView.ToString());
}
else if()...

屏幕名称是导航视图模型中的 属性。

希望对您有所帮助。

导航在 Prism 中不是以跨平台的方式构建的,因此如果没有您自己的代码将无法使用。

为了解决这个问题,在 PCL:

中创建一个 IAppNavigationService 接口
public interface IAppNavigationService
{
    bool Navigate(string pageToken, object parameter);
    void GoBack();
    bool CanGoBack();
}

在Windows项目中实现它,基本上就像INavigationService的包装器,你也可以注入:

public class AppNavigationService : IAppNavigationService
{
   private readonly INavigationService _nav;

   public AppNavigationService( INavigationService navigationService )
   {
      _nav = navigationService;
   } 

   public bool Navigate(string pageToken, object parameter) => 
      _nav.Navigate( pageToken, parameter );

   public void GoBack()
   {
      _nav.GoBack();
   }

   public bool CanGoBack() => _nav.CanGoBack();
}

不要忘记在 App.xaml.cs.

的依赖注入容器中注册 AppNavigationService class

现在,在您的 PCL ViewModel 中,您只需注入并使用 IAppNavigationService 进行导航。