locked
Intercept page leaving event RRS feed

  • Question

  • User254831 posted

    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?

    Monday, February 27, 2017 7:01 AM

All replies

  • User276004 posted

    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.

    Monday, February 27, 2017 7:08 AM
  • User254831 posted

    @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.

    Monday, February 27, 2017 7:10 AM
  • User276004 posted

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

    this will works.

    Monday, February 27, 2017 7:13 AM
  • User254831 posted

    @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;
             }
      }
    
    Monday, February 27, 2017 7:30 AM
  • User356446 posted

    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().

    Friday, August 10, 2018 6:15 PM
  • User2029 posted

    These are the wrong event. For example on Android OnDisappearing is called when the app is backgrounded.

    The correct event is OnParentSet.

        protected override void OnParentSet()
        {
            base.OnParentSet();
            if(Parent == null)
                OnViewClosed();
            else
                OnViewOpened();
        }
    
    Friday, August 7, 2020 10:42 AM