Search code examples
xamarinmvvmcross-platform

when i am using xamarin MVVM. so how to handle Device Back(Hardware back button) in view model


I am creating one app in xamarin cross platform with MVVM, I want to handle device back navigation so how can i handle it? please help me.

Thanks in advanceenter image description here


Solution

  • Well, that's quite simple actually just add a command in your VM and call that command from your View when you need to handle this event!

    In your View

    protected override bool OnBackButtonPressed()
    {
       var vm = (ViewModel)BindingContext;
       if(vm.MyBackPressCommand.CanExecute())  // You can add parameters if any
         {
             MyBackPressCommand.Execute(); // You can add parameters if any
         }
    }
    

    Also, define this in your ViewModel

    public ICommand MyBackPressCommand { get; set; }
    

    And also this needs to be initialized(constructor) like below:

    MyBackPressCommand= new Xamarin.Forms.Command(()=>{});
    

    You can use inheritance to make this globally available for all derived versions of your View/ViewModel