问题
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?
回答1:
Another approach would be to have your page implement INavigationAware
and in the OnNavigatedFrom
, call Navigatin.RemovePage(this)
.
回答2:
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;
}
}
}
回答3:
I do it that way, it's simpler.
navigationService.NavigateAsync("../PageB");
I am using Prims 7.0.0.396.
回答4:
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
来源:https://stackoverflow.com/questions/45084823/xamarin-forms-with-prism-remove-a-page-from-the-stack