GoBackToRootAsync with modal navigation in Prism

Viewed 482

So the application is using modal stack instead of navigation stack, here's a sample of the App class:

protected override async void OnInitialized()
{
    InitializeComponent();
    await NavigationService.NavigateAsync("MainPage");
}

protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
    containerRegistry.RegisterForNavigation<NavigationPage>();
    containerRegistry.RegisterForNavigation<MainPage, MainPageViewModel>();
    containerRegistry.RegisterForNavigation<Page1>();
    containerRegistry.RegisterForNavigation<Page2>();
    containerRegistry.RegisterForNavigation<Page3>();
}

I navigate from MainPage to Page1 to Page2 to Page3, for example, in Page2ViewModel:

public DelegateCommand ToPage3Command => new DelegateCommand(() => 
NavigationService.NavigateAsync("Page3", useModalNavigation: true));

in Page3 I want to go back to the root (MainPage), so I do this:

 public DelegateCommand ToMainPageCommand => new DelegateCommand(async () =>
 {
     var navResult = await NavigationService.GoBackToRootAsync(new NavigationParameters
     { { KnownNavigationParameters.UseModalNavigation, true } });
 });

but navResult.Exception gets a System.InvalidOperationException exception:

Sequence contains no elements

I'm trying this based on the comment by Brian here. but the exception thrown indicates that GoBackToRootAsync only possible with navigation stack: https://github.com/PrismLibrary/Prism/blob/a4c131ab271fcab26c3ed9c5e3eb3316ec02a4ce/Source/Xamarin/Prism.Forms/Navigation/PageNavigationService.cs#L198

If it's not possible with modal stack, is there any workaround without switching to use navigation stack?

The main reason I want to do this is that I want to navigate to the MainPage without re-initializing it and clear the modal stack, so any solution that achieves this is welcome.

0 Answers
Related