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

本文关键字:于页面 操作 按钮 | 更新日期: 2023-09-27 18:00:33

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

由于WP8.1 NavigationHelper非常有用,但它只提供了一个单击返回键(退出页面)的常规操作。

我不能覆盖NavigationHelper,因为它并没有为其命令提供setter,而后退按钮单击的处理程序是私有的,所以我不能在进入页面时取消固定它。在NavigationHelper中进行更改似乎很难看,因为我正在为W8.1&WP8.1和我有多个页面需要自定义后退按钮处理程序。

--编辑--

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

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

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

// in App.xaml.cs make a method and a listOfHandlers:
private List<EventHandler<BackPressedEventArgs>> listOfHandlers = new List<EventHandler<BackPressedEventArgs>>();
private void InvokingMethod(object sender, BackPressedEventArgs e)
{
   for (int i = 0; i < listOfHandlers.Count; i++)
       listOfHandlers[i](sender, e);
}
public event EventHandler<BackPressedEventArgs> 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<BackPressedEventArgs> 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的事件处理程序之前触发,如果您设置了e.Handeled = true;,那么您应该保持在同一页面上。

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

根据添加事件的顺序,添加的事件非常难看。使用NavigationHelper要比绕过它干净得多

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

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