Xamarin.form Page Navigation in mvvm

前端 未结 8 1059
耶瑟儿~
耶瑟儿~ 2021-02-04 03:52

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());

8条回答
  •  无人及你
    2021-02-04 04:19

    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);
            }
     ...
    

提交回复
热议问题