Federico Navarrete
Federico Navarrete

Reputation: 3274

How to handle GoBack in the Navigation Drawer in Windows Phone 8.1?

I'm developing an App using this third party control: DrawerLayout for Windows Phone 8.1

I'm having some problems because most of the examples are finishing the App after closing the Drawer however I have several Frames and I need to go back to the previous one no to the first one.

I think my main problem is because firstly I override the Back Button in the App.xaml.cs with this well-known code:

public App()
{
    this.InitializeComponent();
    this.Suspending += this.OnSuspending;
    this.Suspending += this.OnSuspending;
    HardwareButtons.BackPressed += HardwareButtons_BackPressed;
}

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

    if (frame.CanGoBack)
    {
        frame.GoBack();
        e.Handled = true;
    }
}

However when I implement the Drawer I need to add something like this for handling the Hardware Back Button:

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    HardwareButtons.BackPressed += HardwareButtons_BackPressed;
}

void HardwareButtons_BackPressed(object sender, Windows.Phone.UI.Input.BackPressedEventArgs e)
{
    if (DrawerLayout.IsDrawerOpen)
    {
        DrawerLayout.CloseDrawer();//Close drawer on back press  
        e.Handled = true;
    }
    else
    {
        Frame frame = Window.Current.Content as Frame;
        if (frame == null)
            return;

        if (frame.CanGoBack)
        {
            frame.GoBack();
            e.Handled = true;
        }
    }
}

I have tried different ideas like Adding a public variable, deleting the else (it didn't work because of later it automatically closed the frame). Maybe anyone has any idea how to fix it because I'd like that the first close the drawer and later go back to the previous Frame and it always redirect me to the First one.

Thanks for your worthy time.

Upvotes: 0

Views: 268

Answers (1)

Muhammad Saifullah
Muhammad Saifullah

Reputation: 4292

Actullay OnNavigateTo Method is called when the frame is navigated to (opened) and OnNavigatedFrom method is called when frame is closed. You need to register Hardware backpress on OnNavigateTo and unregister it in OnNavigateFrom.

See the example:

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    Windows.Phone.UI.Input.HardwareButtons.BackPressed += HardwareButtons_BackPressed;
}

protected override void OnNavigatedFrom(NavigationEventArgs e)
{
    Windows.Phone.UI.Input.HardwareButtons.BackPressed -= HardwareButtons_BackPressed;
}

Upvotes: 1

Related Questions