2016-04-14 51 views
3

我有Prism和AppShell的UWP應用程序。 我想在BackButton退出前添加確認對話框。 我嘗試這樣做:如何在UWP中處理HardwareButtons.BackPressed?

protected override Task OnLaunchApplicationAsync(LaunchActivatedEventArgs args) 
    { 
     ... 
     SystemNavigationManager.GetForCurrentView().BackRequested += App_BackRequested; 

     ... 
    } 

private void App_BackRequested(object sender, BackRequestedEventArgs e) 
    { 
     Frame rootFrame = Window.Current.Content as Frame; 
     if (rootFrame == null) 
     { 
      return; 
     } 

     if (rootFrame.CanGoBack && e.Handled == false) 
     { 
      <add confirm dialog here> 
      e.Handled = true; 
     } 
    } 

但rootFrame總是爲null,如果歷史堆棧空的,我按下返回按鈕的應用有即使imake的是:

private void App_BackRequested(object sender, BackRequestedEventArgs e) 
{ 
     e.Handled = true; 
} 

我也試過

HardwareButtons.BackPressed += App_BackRequested; 

它也沒有幫助。

回答

1

嘗試以下行添加到這些OnLaunchApplicationAsync方法

protected override Task OnLaunchApplicationAsync(LaunchActivatedEventArgs args) 
    { 
     //...... 
     DeviceGestureService.GoBackRequested += (s, e) => 
     { 
      e.Handled = true; 
      e.Cancel = true; 
      if (NavigationService.CanGoBack()) 
      { 
       NavigationService.GoBack(); 
      } 
      else 
      { 
       // PUT YOUR LOGIC HERE (Confirmation dialog before exit) 
       Application.Current.Exit(); 
      } 
     }; 
     //...... 
    } 
+0

+1。如果您通過此解釋您實現的目標,則PO更易於理解您如何解決問題。使用Prism的 –

+0

提供了處理硬件按鈕事件的能力,如(CameraButtonReleased,CameraButtonPressed,CameraButtonHalfPressed,GoBackRequested,.....)只是在OnLaunchApplicationAsync方法中實現它 –

2

在App.xaml.cs添加代碼 -

private async void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e) 
    { 

     e.Handled = true; 
     Frame rootFrame = Window.Current.Content as Frame; 
     if (rootFrame.CanGoBack && rootFrame != null) 
     { 

      rootFrame.GoBack(); 
     } 
     else 
     { 
      var msg = new MessageDialog("Confirm Close"); 
      var okBtn = new UICommand("OK"); 
      var cancelBtn = new UICommand("Cancel"); 
      msg.Commands.Add(okBtn); 
      msg.Commands.Add(cancelBtn); 
      IUICommand result = await msg.ShowAsync(); 

      if (result != null && result.Label == "OK") 
      { 
       Application.Current.Exit(); 
      } 
     } 
    } 

加入這一行App.xaml.cs的構造 -

HardwareButtons.BackPressed += HardwareButtons_BackPressed; 
+0

它在新的空白項目上工作,但不能在我的應用程序中工作。 rootFrame始終爲空,如果我在關閉彈出式應用程序時按NO。我認爲這是因爲我有這個: 保護覆蓋UIElement CreateShell(Frame rootFrame) {shell} = Container.Resolve (); shell.SetContentFrame(rootFrame); return shell; } –