Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin Forms with Prism: Remove a page from the stack

When I navigate from page A to page B, I need to remove page A.

How can I do this with Prism's navigation service in Xamarin Forms?

like image 543
Don Box Avatar asked Oct 30 '25 15:10

Don Box


2 Answers

There are a few scenarios that people run into on this one.

As a common example say you have a LoginPage, and once the user successfully logs in you want to Navigate to the MainPage. Your code might look something like the following:

public class App : PrismApplication
{
    protected override async void OnInitialized()
    {
        await NavigationService.NavigateAsync("LoginPage");
    }

    protected override void RegisterTypes()
    {
        Container.RegisterTypeForNavigation<LoginPage>();
        Container.RegisterTypeForNavigation<MainPage>();
    }
}

public class LoginPageViewModel : BindableBase
{
    public DelegateCommand LoginCommand { get; }

    private async void OnLoginCommandExecuted()
    {
        // Do some validation

        // Notice the Absolute URI which will reset the navigation stack
        // to start with MainPage
        await _navigationService.NavigateAsync("/MainPage");
    }
}

Now if what you're looking for is some flow where your navigation stack looks like MainPage/ViewA and what you want is MainPage/ViewB and you don't want to reinitialize MainPage, then this is something that we are currently evaluating and wanting to improve this so you could do something like _navigationService.NavigateAsync("../ViewB"). In the mean time what I might suggest is something like this:

public class ViewAViewModel : BindableBase
{
    public DelegateCommand ViewBCommand { get; }

    private async void OnViewBCommandExecuted()
    {
        var parameters = new NavigationParameters
        {
            { "navigateTo", "ViewB" }
        };

        await _navigationService.GoBackAsync(parameters);
    }
}

public class MainPageViewModel : BindableBase, INavigatedAware
{
    public async void OnNavigatingTo(NavigationParameters parameters)
    {
        if(parameters. GetNavigationMode() == NavigationMode.Back && 
           parameters.TryGetValue("navigateTo", out string navigateTo))
        {
            await _navigationService.NavigateAsync(navigateTo);
            return;
        }
    }
}
like image 83
Dan Siegel Avatar answered Nov 03 '25 13:11

Dan Siegel


Given: "NavigationPage/ViewA/ViewB/ViewC/ViewD"

Navigate from ViewD with: NavigationService.NavigateAsync("../../../ViewE");

Results in: "NavigationPage/ViewA/ViewE"

Referred from here

Need Prism >= 7.0

like image 42
Dinesh Phalwadiya Avatar answered Nov 03 '25 13:11

Dinesh Phalwadiya