I strongly advise to use Prism, facilitates navigation problems as described here, and using the model MVVM(Model View Viewmodel), to better distribute and establish responsibilities in a mobile application.
Here is a brief summary of how the Navigation in Prism before moving on to the solution:
EN: Navigating in a Prism application is conceptually Different than standard navigation in Xamarin.Forms. While Xamarin.Forms navigation relies on a Page class instance to navigate, Prism removes all dependencies on Page types to Achieve loosely Coupled navigation from Within a Viewmodel. In Prism, the Concept of navigating to a View or navigating to a Viewmodel does not exist. Instead, you Simply navigate to an Experience, or a Unique Identifier, which represents the target view you Wish to navigate to in your application.
PT: Navigating in a Prism application is conceptually different from the standard navigation in Xamarin.Forms. Although Xamarin.Forms navigation relies on an instance of the Page class to navigate, Prism removes all page type dependencies to get a linked navigation from a Viewmodel. In Prism, the concept of navigating to a View or navigating to a Viewmodel does not exist. Instead, just navigate to a unique experience or identifier, which represents the destination view you want to navigate to in the application.
Now for the Solution:
1º - Make the Viewmodels extend the Viewmodelbase (generated by Prism in the creation of a project), to access the navigation interface in the constructor and save it.
public class MainPage: ViewModelBase
{
INavigationService _navigationService;
public MainPage(INavigationService navigationService): base(navigationService)
{
_navigationService = navigationService;
}
}
2º - Override the methods Onnavigatedto and Onnavigatedfrom, when you sail for a page, and for when you browse of a page respectively
Search pageviewmodel.Cs
public override void OnNavigatedFrom(INavigationParameters parameters)
{
base.OnNavigatedFrom(parameters);
}
public override void OnNavigatedTo(INavigationParameters parameters)
{
base.OnNavigatedTo(parameters);
}
3º - Navigation to the pages is done as follows:
_navigationService.NavigateAsync("PesquisaPage");//O identificador é o nome do ficheiro da view, (Por convenção, em Prism, o *naming* das páginas termina sempre em "Page")
4º - imagine that we want to pass a string of Search pageviewmodel to the Mainpageviewmodel, as we want to move to the previous page (the equivalent of popasync), we do Onnavigatedfrom:
public override void OnNavigatedFrom(INavigationParameters parameters)
{
string nome = "Ricardo"
parameters.Add("KeyDoObjeto", nome);//Add(Key, Obj)
base.OnNavigatedFrom(parameters);
}
5th - Finally, in the Mainpageviewmodel we get the string in Onnavigatedto
public override void OnNavigatedTo(INavigationParameters parameters)
{
base.OnNavigatedTo(parameters);
string nomeVindoDaPesquisaPage = (string)parameters["KeyDoObjeto"];
}