Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows phone 8.1 BackPressed not working properly

Windows phone 8.1 new to world. Basic function is back button click. Is that function not working properly is this windows phone 8.1. Is that behavior or i'm made mistake.

Below code using in Homepage but this code calling from all other class too while clicking back. I need to access below method only on Home page .

Please check below code and refer me good solution.

Please look my code:

 public HomePage()
 {
  this.InitializeComponent(); 
  Windows.Phone.UI.Input.HardwareButtons.BackPressed += HardwareButtons_BackPressed;
 }

    void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)
    {

    }

Thanks

like image 949
Jeeva123 Avatar asked Dec 25 '22 07:12

Jeeva123


1 Answers

It is working properly. The BackPressed event is working app-wide. Two options that come to my mind:

  • write eventhandler that would recognize the Page in which you currently invoke it - simple example can look like this:

    private void HardwareButtons_BackPressed(object sender, Windows.Phone.UI.Input.BackPressedEventArgs e)
    {
        Frame frame = Window.Current.Content as Frame;
        if (frame == null) return;
    
        if (frame.Content is HomePage)
        {
            e.Handled = true;
            Debug.WriteLine("I'm in HomePage");
        }
        else if (frame.CanGoBack)
        {
            frame.GoBack();
            e.Handled = true;
        }
    }
    
  • second option - subscribe to Windows.Phone.UI.Input.HardwareButtons.BackPressed when you enter the Page and unsubscribe when you leave the Page. Note that in this way there are some pitfalls - you have to handle properly OnNavigatedTo, OnNavigatedFrom, Suspending and Resuming (more about Lifecycle here). Note also that the subscription should be done before others - for example NavigationHelper.

Some remarks - the above code should work, but it also depends on other circumstances:

  • if there is something other subscribed to BackPressed before (in App.xaml.cs) - remember that usually events are fired in order they were subscribed
  • check if you are using NavigationHelper - it also subscribes to BackPressed
  • remember not to subscribe multiple times
  • remember to allow the User to leave your HomePage
like image 52
Romasz Avatar answered Jan 22 '23 03:01

Romasz