Forum Xamarin.Forms
We are excited to announce that the Xamarin Forums are moving to the new Microsoft Q&A experience. Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

We encourage you to head over to Microsoft Q&A for .NET for posting new questions and get involved today.

How to control Navigation in Xamarin forms

Hi,
I've been facing a problem on navigation on my apps. I've some Modal page i need to close them when physical back button press and go to immediate previous page. When apps land on main landing page if user press physical back button apps ask a question is "Want to exit". But couldn't get the current page when apps in Modal page. It directly goes Main Landing page and showing the exit message. How can i control this.

Thanks in advance.

Tagged:

Best Answer

Answers

  • stXamDevstXamDev Member ✭✭✭

    @baruasgrps can you simplify your use case, you want to override the back button in case of a modal page? is that it

  • baruasgrpsbaruasgrps Member ✭✭

    @JuniorJiang said:
    Hi, @baruasgrps , you could store a page flag type when each page shows to achieve that. And the page flag type only need to define two type: **One **is 0(means main page), **another **is 1(other pages). Then when pressing physical back button, you can determine whether need to show the exit message to exit the app.

    For example, using Xamarin.Essentials: Preferences to store flag in OnAppearing method of each page:

    MainPage:

        public partial class MainPage: ContentPage
        {
            public MainPage()
            {
                InitializeComponent();
            }
    
            protected override void OnAppearing()
            {
                base.OnAppearing();
                Preferences.Set("PageType", "0");
            }
        }
    

    OtherPage:

        public partial class OtherPage : ContentPage
        {
            public OtherPage()
            {
                InitializeComponent();
            }
    
            protected override void OnAppearing()
            {
                base.OnAppearing();
                Preferences.Set("PageType", "1");
            }
        }
    

    Then in Android OnKeyDownmethod to determine whether need to show exit message:

    public override bool OnKeyDown([GeneratedEnum] Keycode keyCode, KeyEvent e)
    {
        var pageType = Preferences.Get("PageType", "0");
        if (keyCode == Keycode.Back && e.RepeatCount == 0) {
            if(pageType == "0")
            {
                ShowExitMessage();
            }
            return true;
        }
        return base.OnKeyDown(keyCode, e);
    }
    

    Thanks for reply. Its work for me.

Sign In or Register to comment.