后退按钮的基于页面的操作

我的问题是如何为给定页面定义自己的操作,即首先单击后退按钮关闭弹出窗口,然后从页面导航?

由于WP8.1 NavigationHelper非常有用,它只给出了一个用于单击后退键(退出页面)的一般操作。

我无法覆盖NavigationHelper,因为它没有为其命令设置setter,后退按钮点击的处理程序是私有的,所以我无法在输入页面时取消固定它。 由于我正在为W8.1和WP8.1开发通用应用程序,因此在NavigationHelper中进行更改似乎很难看,而且我有多个页面需要自定义处理程序来执行后退按钮。

– 编辑 –

命令允许覆盖,但我将在每个页面上使用原始命令。 解决方案是在每个页面上创建新命令?

我认为您可以在NavigationHelper之前订阅Windows.Phone.UI.Input.HardwareButtons.BackPressed (因为我已经检查过它在Page.Loaded事件中订阅)。 实际上为了这个目的(因为稍后你将添加EventHandlers),你需要一个特殊的InvokingMethod来调用你的EventHandlers:

 // in App.xaml.cs make a method and a listOfHandlers: private List> listOfHandlers = new List>(); private void InvokingMethod(object sender, BackPressedEventArgs e) { for (int i = 0; i < listOfHandlers.Count; i++) listOfHandlers[i](sender, e); } public event EventHandler myBackKeyEvent { add { listOfHandlers.Add(value); } remove { listOfHandlers.Remove(value); } } // look that as it is a collection you can make a variety of things with it // for example provide a method that will put your new event on top of it // it will beinvoked as first public void AddToTop(EventHandler eventToAdd) { listOfHandlers.Insert(0, eventToAdd); } // in App constructor: - do this as FIRST eventhandler subscribed! HardwareButtons.BackPressed += InvokingMethod; // subscription: (App.Current as App).myBackKeyEvent += MyClosingPopupHandler; // or (App.Current as App).AddToTop(MyClosingPopupHandler); // it should be fired first // also you will need to change in NavigationHelper.cs behaviour of HardwereButtons_BackPressed // so that it won't fire while e.Handeled == true private void HardwareButtons_BackPressed(object sender, Windows.Phone.UI.Input.BackPressedEventArgs e) { if (!e.Handled) { // rest of the code } } 

在这种情况下,BackPressed将在NavigationHelper的eventhandler之前触发,如果你设置了e.Handeled = true; 那么你应该留在同一个页面上。

另请注意,您可以通过这种方式扩展您的Page类或NavigationHelper,而不是修改App.xaml.cs,这取决于您的需求。

根据订单的顺序添加事件非常难看。 使用NavigationHelper比尝试绕过它更干净。

您可以将自己的RelayCommand设置为NavigationHelper的GoBackCommand和GoForewardCommand属性。 另一种选择是子类化NavigationHelper并覆盖CanGoBack和GoBack函数(它们是虚拟的)。

无论哪种方式,您都可以使用自定义逻辑替换NavigationHelper的默认操作,以关闭任何中间状态或根据需要调用Frame.GoBack。