Search code examples
windows-8.1user-input

Stop users going from one page to another page


I want to stop users going from one frame/page back to the main previous page.

For example, when the user successfully logs in they are to go to the users list page.

If a user presses the hardware back button from the users list page, then they shouldn't go back to the login screen. If they do, the program should either prompt with two buttons, yes to logout and go back to the login screen, or no and stay on the current screen.

        private void HardwareButtons_BackPressed(object sender, Windows.Phone.UI.Input.BackPressedEventArgs e)
    {
        Frame frame = Window.Current.Content as Frame;
        if (frame == null) return;

        //the current frame is UserList
        if (frame.Content is UserList)
        {
            messageBox("yes");
            e.Handled = true;
        }
        else if (frame.CanGoBack)
        {
            frame.GoBack();
            e.Handled = true;
        }
    }

In theory, if the current frame is the user list page, then do not go back.

How can I stop a user from going back a page?


Solution

  • First you need to attach the event to HardwareButtons back button which is available in Windows.UI.Xaml.Input namespace. Add this below InitializeComponent call in page constructor.

    HardwareButtons.BackPressed += HardwareButtons_BackPressed;
    

    If you just handle the event it is enough to prevent user from going back with hardware back button.

    private void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)
    {
        e.Handled = true;
    }
    

    If you don't want to allow the user to go back if the previous page is Login page you can try this.

    private void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)
    {
        e.Handled = true;
        if (Frame.BackStack.Last().SourcePageType.Equals(typeof(LoginPage)))
        {
            //TODO: handle prompt
        } else {
            Frame.GoBack();
        }
    }
    

    ps: if you handle e you should provide Frame.GoBack(); manually otherwise users will be stuck in that page.