【问题标题】:Page-based action for back button后退按钮的基于页面的操作
【发布时间】:2014-04-29 02:14:06
【问题描述】:

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

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

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

--编辑--

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

【问题讨论】:

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


    【解决方案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,这取决于您的需要。

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-12
      • 1970-01-01
      • 1970-01-01
      • 2012-12-24
      • 2016-03-08
      • 1970-01-01
      • 2017-06-25
      • 1970-01-01
      相关资源
      最近更新 更多