How to use Navigation.InsertPageBefore in a ViewModel class in xamarin forms?

Hi

I was using the below code in my previous application to remove login page from the stack once the user has successfully logged in.

                                        var supervisor = new Supervisor();
                                        Navigation.InsertPageBefore(supervisor, this);
                                        Navigation.PopAsync();
                                        btnLogin.IsEnabled = true;
                                        Spinner.IsEnabled = false;

I want to do the same in a viewmodel class where I am not able to use "this" keyword as it represents a page. So is there any other way in which I can accomplish my task.
Any help will be greatly appreciated.

Regards

Best Answer

  • FouziyaFouziya ✭✭
    Accepted Answer

    Hi

    I found a simple solution for the problem, In MVVM where you have to make your Page as root page then just use

    Application.Current.MainPage = new NavigationPage(new Supervisor());

    This line will remove your login page from the stack and make the MasterDetail page(in this case Supervisor page) as your root page.

    Hope this helps to someone.

    Thank you

Answers

  • seanydaseanyda GBMember ✭✭✭✭✭
    edited September 2018

    I'm not sure what you're asking. Are you asking can you access the Navigation method from your ViewModel? If so I normally just pass it back.

    Create a property in your BaseViewModel or ViewModel like this

    public INavigation Navigation { get; set; }
    

    When you create a ContentPage pass the ViewModel in the ctor and pass back the Navigation event

    public PageOne(PageOneViewModel vm)
            {
                BindingContext = vm;
                vm.Navigation = this.Navigation;
            }
    

    You can now do Navigation calls from the ViewModel.

  • FouziyaFouziya Member ✭✭
    Accepted Answer

    Hi

    I found a simple solution for the problem, In MVVM where you have to make your Page as root page then just use

    Application.Current.MainPage = new NavigationPage(new Supervisor());

    This line will remove your login page from the stack and make the MasterDetail page(in this case Supervisor page) as your root page.

    Hope this helps to someone.

    Thank you

Sign In or Register to comment.