Xamarin.Forms Go to another page using ViewModel

I have several ContentPages, and I want to go from one to another when I click an element on the page. I have a 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 appropriate 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 to click an image to execute a command in the JumpVM class, and go to the page there. How can i do this?

+7
c # mvvm xamarin xamarin.forms
source share
4 answers

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

+1
source share

This is the answer for moving one page to another page in the ViewModel concept.

 public ICommand NavigationList { get; set; } NavigationList = new Command(GetListview); public void GetListview() { Xamarin.Forms.Application.Current.MainPage.Navigation.PushAsync(new ListViewPerson()); } 
+6
source share

If you use ViewModels, you can easily implement this with ICommand.

 namespace YourApp.ViewModels { public class CurrentPageViewModel { public ICommand BackToPage {get; private set; } public CurrentPageViewModel() { BackToPage = new Command(async () => { await Application.Current.MainPage.Navigation.PushModalAsync(new MainPage()); }); } } } 

And in the ViewModel of the page you want to go to, you need to implement PopAsync as follows.

 namespace YourApp.ViewModels { public class MainPageViewModel { public ICommand BackToMain { get; private set; } public MainPageViewModel() { BackToMain = new Command(async () => { await Application.Current.MainPage.Navigation.PopAsync(); }); } } } 

Also, do not forget to use the bindings in your CodeBehind views both on the current page and in the fact that you want to do so.

 namespace RealmApp1.Views { public partial class MainPage : ContentPage { public MainPage() { InitializeComponent(); BindingContext = new MainPageViewModel(); } } } 

Hope this works for you! Have a good code!

0
source share

this is what i do

I use the following helper class

https://gist.github.com/julesx/4a3b68ef7f7eda8572ae5755e3665d47

0
source share

All Articles