我认为您可以Windows.Phone.UI.Input.HardwareButtons.BackPressed
在 NavigationHelper 之前订阅(正如我在 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,这取决于您的需要。