Shell/Flyout Navigation Bar - Back Button Pressed - want to intercept in ViewModels c# file

Riffy 276 Reputation points


I am using Visual Studio 2022/xamarin/C# to develop my App.

I am trying to resolve an issue where I want to intercept the pressing of the Back Button on the Shell Navigation Bar, for one of my pages, so I can execute some c# code in my ViewModel.

I know you can use the OnDisappearing() module in the View Page, but I want to use it in the ViewModel code behind.

Have look at various solutions, but they don't work.

Also does the page/data get cleared from memory when back button is pressed?


A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,302 questions
0 comments No comments
{count} votes

Accepted answer
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 69,616 Reputation points Microsoft Vendor


    You can bind a Command to Back Button in Shell, then execute some c# code in your ViewModel's command event.

    For example, I have a detailed page, I add Shell.BackButtonBehavior and bind a BackButtonCommand

       <ContentPage xmlns=""  
                    Title="{Binding Title}">  
               <BackButtonBehavior Command="{Binding BackButtonCommand}"/>  

    We can execute some C# code in the ViewModel when click the back button.

       public ICommand BackButtonCommand { get; set; }  
              public ItemDetailViewModel()  
                   BackButtonCommand = new Command(async () => {  
                       //Execute your code when click the back button in the shell  
                      //navigate to the previous page  
                     await  Shell.Current.GoToAsync("..");  

    Best Regards,

    Leon Lu

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful