Intercept page leaving event

DevJDevJ CHMember ✭✭

Basically I would like to ask the user, if he really wants to move away from the current page. How would I do that? I have a MasterDetailPage. Is there an event like the disappearing but before the page gets destroyed?

Answers

  • PankitPatelPankitPatel USMember ✭✭

    protected override bool OnBackButtonPressed() { ShowExitDialog(); }

    private async void ShowExitDialog() { var answer = await DisplayAlert(AppResources.LApplicationName, AppResources.LExitApp, AppResources.LYes, AppResources.LNo); if (answer) { if (Device.OS == TargetPlatform.Android) { //DependencyService.Get<ICloseApp>().CloseApp(); var closeApp = DependencyService.Get<ICloseApp>(); closeApp.CloseApp(); } OnBackButtonPressed(); } }

    You can Use Dependency Service for asking as Alert Box.
    In my case I asked for Exit Application in Home Page and it is working fine for me.

    Interface for Dependency Service in Xamarin Forms Portable Project.
    public interface ICloseApp { void CloseApp(); }

    Let me know if any problem.

  • DevJDevJ CHMember ✭✭

    @PankitPatel The thing is, this event doesn't get fired if the user moves away using the navigation buttons in my MasterDetailPanel. It only fires, when the backbutton gets hit.

  • PankitPatelPankitPatel USMember ✭✭

    Then you need to add event like below
    protected override void OnDisappearing() { base.OnDisappearing(); }

    this will works.

  • DevJDevJ CHMember ✭✭
    edited February 2017

    @PankitPatel It does not work..

    protected override void OnDisappearing()
    {
           ShouldExit();         
    }
    
     private async void ShouldExit()
     {
            var tmpShouldExit = await DisplayAlert("a", "b", "c", "d");
            if (tmpShouldExit)
            {
                base.OnDisappearing();
                CurrentConnectivity.Instance.ConnectivityChanged -= CurrentOnConnectivityChanged;
             }
      }
    
  • Eric.ReevesEric.Reeves USMember ✭✭

    I know this is super old but to handle this your best option would be to push a page modally. From the modally pushed page you can control how the page handles much easier by adding your own controls rather than relying on the Xamarin navigation controls. That way you can just call ShouldExit() from an OnTappedEvent().

Sign In or Register to comment.