1
votes

I'm making app in Xamarin with MVVMCross. This is my code:

Android View (iOS is almost the same):

var button = (Button)FindViewById(Resource.Id.button3);
var set = this.CreateBindingSet<MenuView, MenuViewModel>();
set.Bind(button).To(vm => vm.CommandNavigateToSecondPage);
set.Apply();

Core ViewModel:

public ICommand CommandNavigateToSecondPage
{
    get
    {
        return new MvxCommand((() =>
        {
            ShowViewModel<SecondPageViewModel>();
        }));
    }
}

I want to have a default back button that will navigate me to previous page. I made same navigation with simple function in core and there was back button. Like this:

public void Navigate()
{
    ShowViewModel<SecondPageViewModel>();
}

MVVM is all about binding this is why I want to make it in this way.

1
To move back to the previous ViewModel you can simply use Close(this); - Fahadsk
I know. But i didn't had the back button on my action bar. I figured out that I need to remove the SupportActionBar.SetDisplayHomeAsUpEnabled(true) line in "OnCreate" (and same in iOS). I do not know where this method came from. On iOS the back navigation works but when i click the back button in Android nothing happen :/ Do I need to override BackButton default method ? - OskarS

1 Answers

1
votes

To display default home/back button in android

[Activity (Label = "MyView")]           
public class MyView : MvxActivity
{
    protected override void OnCreate (Bundle bundle)
    {
        base.OnCreate (bundle);
        SetContentView(Resource.Layout.ThirdNativeView);

        ActionBar.SetDisplayHomeAsUpEnabled(true);
    }
    /// handle back navigation here
    public override bool OnOptionsItemSelected(IMenuItem item)
    {
        switch (item.ItemId)
        {
            case Android.Resource.Id.Home:
                //Execute viewModel command here
                this.Finish();
                return true;
            default:
                return base.OnOptionsItemSelected(item);
        }
    }
}

more info on executing command here