Xamarin.Forms Navigate to another page using ViewModel

12,552

Solution 1

Try adding the following line after the FadeTo line: ((JumpVM)BindingContext).NewPage.Execute(null).

Solution 2

This is Answer for Navigating one page to another page in ViewModel concept.

public ICommand NavigationList { get; set; }

NavigationList = new Command(GetListview);  

public void  GetListview()
{
   Xamarin.Forms.Application.Current.MainPage.Navigation.PushAsync(new ListViewPerson());
}
Share:
12,552
Dragos
Author by

Dragos

Updated on June 17, 2022

Comments

  • Dragos
    Dragos about 2 years

    I have several ContentPages and I want to navigate from one to another at the click of an element in the page. I have my ViewModel class:

     class JumpVM : INotifyPropertyChanged
        {
            public event PropertyChangedEventHandler PropertyChanged;
            private INavigation _navigation;
    
            public ICommand NewPage
            {
                get
                {
                    return new Command(async () =>
                    {
                        await _navigation.PushAsync(new MySettingsPage());
                    });
                }
            }
    
            public JumpVM() { }
    
            public JumpVM(INavigation navitation)
            {
                _navigation = navitation;
            }
        }
    

    And this is one of my pages( for the sake of space, i put only the relevant code):

    BindingContext = new JumpVM(this.Navigation);
    

    ....

     Image fbInvite = new Image
                {
                    Source = ImageSource.FromResource(Constants.ASSETLOCATION + ".facebookInviteIcon.png"),
                    HorizontalOptions = LayoutOptions.Center
                };
                fbInvite.GestureRecognizers.Add(new TapGestureRecognizer(sender =>
                    {
                        //navigation in the method below
                        FaceboonInviteFriends();
                        fbInvite.Opacity = 0.8;
                        fbInvite.FadeTo(1);
                    }));
    

    I want when I click the image, to execute the Command in the JumpVM class and navigate to the page there. How can I do that?

  • Toni Petrina
    Toni Petrina over 9 years
    Actually, it does answer. I will add just a small hint to my answer.
  • Dragos
    Dragos over 9 years
    Thank you :) That helped. I'm gonna mark as answered, but if you can help me with another thing related to this, would be nice. As you can see I've hard coded where it would jump " await _navigation.PushAsync(new MySettingsPage());" . But for more flexibility, can I put a certain page there depending on what button I click?
  • Toni Petrina
    Toni Petrina over 9 years
    Sure, you can create any page you want and use it as a parameter.
  • Dragos
    Dragos over 9 years
    Like BindingContext = new JumpVM(new MyNewPage(),this.Navigation);?