在uwp中覆盖后退按钮

时间:2016-03-25 09:39:27

标签: c# win-universal-app

正如oficial doc中提到的那样,有可能处理后退按钮按下,但我无法处理它只做我的逻辑而不回去。所以我的代码看起来像:

//declare event
public event EventHandler<BackRequestedEventArgs> BackRequested;

public MainPage() {
  InitializeComponent();

  // tie my event with back action
  SystemNavigationManager.GetForCurrentView().BackRequested += OnBackRequested;
}

// handle the back event
private void OnBackRequested(object sender, BackRequestedEventArgs e) {
  //need to do only my logic here  - do NOT go back 
}

有没有办法来解决这个问题。我喜欢它,就像Android那样:

@Override
public void onBackPressed() {
  //does only my logic
}

1 个答案:

答案 0 :(得分:1)

您可以将参数参数e.Handled设置为true,以便它可以实现您自己的逻辑,您可以选择是否返回堆栈。

    private void OnBackRequested(object sender, BackRequestedEventArgs e)
    {
        Frame rootFrame = Window.Current.Content as Frame;

        if (rootFrame.CanGoBack)
        {
            e.Handled = true;

            if(condition) //my condition is true so go back through the stack
                rootFrame.GoBack();
            }
        }
    }