I'm building a UWP application with PCL using prism.
PCL contains the ViewModels
UWP contains the Views
My problem is I cannot use INavigationService in the PCL so I can't really navigate to other pages.
Here is my code:
<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>
public class NavigationRootViewModel : BindableBase
{
public ICommand SecondPageCommand { get; set; }
public NavigationRootViewModel()
{
SecondPageCommand = DelegateCommand.FromAsyncHandler(ExecuteMethod);
}
private Task ExecuteMethod()
{
return Task.FromResult(0);
}
}
My wish was to inject INavigationService in the constructor but it's not part of the Prism.Core dll.
So what is the correct way to do it? Is it even possible to navigate in PCL using Prism ? in MvvmCross it is...
Navigation is not built in a cross-platform manner in Prism, so it will not work without your own code.
To solve this, create an IAppNavigationService
interface in the PCL:
public interface IAppNavigationService
{
bool Navigate(string pageToken, object parameter);
void GoBack();
bool CanGoBack();
}
Implement it in the Windows project, basically just as a wrapper around the INavigationService
, which you can also inject:
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();
}
Do not forget to register the AppNavigationService
class in the dependency injection container in App.xaml.cs
.
Now in your PCL ViewModels you can just inject and use the IAppNavigationService
for navigation.