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

Riffy 276 Reputation points
2022-10-10T17:36:35.977+00:00

Hi

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?

Thanks

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

Accepted answer
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 72,336 Reputation points Microsoft Vendor
    2022-10-11T06:23:10.007+00:00

    Hello,

    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="http://xamarin.com/schemas/2014/forms"  
                    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"  
                    x:Class="App2.Views.ItemDetailPage"  
                    Title="{Binding Title}">  
           <Shell.BackButtonBehavior>  
               <BackButtonBehavior Command="{Binding BackButtonCommand}"/>  
           </Shell.BackButtonBehavior>  
    

    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