Xamarin.form Page Navigation in mvvm

前端 未结 8 1081
耶瑟儿~
耶瑟儿~ 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:34

    my approach based on principle every View can navigate to VM context based places of the app only:

    In ViewModel i declare INavigationHandler interfeces like that:

    public class ItemsViewModel : ViewModelBase
    {
        public INavigationHandler NavigationHandler { private get; set; }
    
    
        // some VM code here where in some place i'm invoking
        RelayCommand ItemSelectedCommand => 
            new RelayCommand((itemID) => { NavigationHandler.NavigateToItemDetail(itemID); });
    
    
        public interface INavigationHandler
        {
            void NavigateToItemDetail(int itemID);
        }
    }
    

    And assign code-behind class as INavigationHandler for ViewModel:

    public class ItemsPage : ContentPage, ItemsViewModel.INavigationHandler
    {
        ItemsViewModel viewModel;
    
        public ItemsPage()
        {
            viewModel = Container.Default.Get();
            viewModel.NavigationHandler = this;
        }
    
    
        public async void NavigateToItemDetail(int itemID)
        {
            await Navigation.PushAsync(new ItemDetailPage(itemID));
        }
    }
    

提交回复
热议问题