I am working on xamarin.form cross-platform application , i want to navigate from one page to another on button click. As i cannot do Navigation.PushAsync(new Page2());
Passing INavigation through VM constructor is a good solution indeed, but it can also be quite code-expensive if you have deep nested VMs architecture.
Wrapping INavigation with a singleton, accesible from any view model, is an alternative:
NavigationDispatcher Singleton:
public class NavigationDispatcher
{
private static NavigationDispatcher _instance;
private INavigation _navigation;
public static NavigationDispatcher Instance =>
_instance ?? (_instance = new NavigationDispatcher());
public INavigation Navigation =>
_navigation ?? throw new Exception("NavigationDispatcher is not initialized");
public void Initialize(INavigation navigation)
{
_navigation = navigation;
}
}
Initializing in App.xaml.cs:
public App()
{
InitializeComponent();
MainPage = new NavigationPage(new MainPage());
NavigationDispatcher.Instance.Initialize(MainPage.Navigation);
}
Using in any ViewModel:
...
private async void OnSomeCommand(object obj)
{
var page = new OtherPage();
await NavigationDispatcher.Instance.Navigation.PushAsync(page);
}
...