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

时间:2014-04-29 02:14:07

标签: c# windows-phone-8.1 win-universal-app

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

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

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

- 编辑 -

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

2 个答案:

答案 0 :(得分:4)

我认为您可以在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,这取决于您的需求。

答案 1 :(得分:1)

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

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

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