【问题标题】:Overriding the Back Button in Prism for Windows Phone 8.1 Runtime为 Windows Phone 8.1 运行时覆盖 Prism 中的后退按钮
【发布时间】:2014-10-16 17:39:03
【问题描述】:

我在一个 Windows Phone 8.1 项目中使用用于 WinRT 的 Prism MVVM 库。是否可以通过手机的后退按钮阻止后退导航并处理 ViewModel 中的后退按钮按下?

具体场景:

  • 用户可以从项目列表中选择一个项目(“活动”项目) - 就像游戏中的玩家一样。该项目是应用程序其余功能的参考,例如数据库查询。
  • 选择一项会将用户返回到上一个(主)页面。
  • 在同一个列表中,用户还可以删除不再需要的项目。应该可以删除所有项目。

问题:如果用户删除活动项或最后一项,然后点击后退按钮,我最终会得到一个无效的活动项。

为了防止这种情况,我想取消后退按钮导航并提示用户选择或创建另一个活动项,最好是从 ViewModel 中。


更新:我现在已经根据我对 Nate 下面评论的理解,向 App.xaml.cs 添加了一个事件处理程序。这应该在应用程序范围内覆盖它:

private void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)
{
    Frame currentFrame = Window.Current.Content as Frame;
    if (currentFrame == null)
    {
        return;
    }
    if (currentFrame.Content is SelectionPage)
    {
        e.Handled = true;
    }
    else if (currentFrame.CanGoBack)
    {
        currentFrame.GoBack();
        e.Handled = true;
    }
}

并在构造函数中订阅事件:

#if WINDOWS_PHONE_APP
        HardwareButtons.BackPressed += HardwareButtons_BackPressed;
#endif

这似乎可以很好地处理后退按钮按下,但它不会停止现有的导航。所以它在任何情况下都会返回,在默认情况下会返回两次。

【问题讨论】:

  • 您必须使用 HardwareButtons.BackPressed 在应用程序本身中取消平台上的后退按钮导航。然后,您可以使用它执行任何您想要的逻辑,无论是应用程序范围的逻辑还是特定于页面的逻辑。确保在事件 args 中将 Handled 设置为 true
  • @NateDiamond 感谢您的帮助。我是否理解这意味着取消 Prism 在应用程序级别提供的整个导航服务?这似乎相当激进。它还会将使用信息的导航逻辑从 ViewModel 移动到 View 中吗?有没有办法覆盖 Prism 框架内特定页面的后退导航?
  • 对于任何想知道同样问题的人:当然有一种解决方法,在返回页面的 OnNavigatedTo() 中处理此问题,将用户弹回选择页面。不过看起来不干净。
  • 如果您在 app.xaml.cs 中添加一个事件,那么它会在整个应用程序中拦截它。但是,如果您只在页面上拦截它并在离开页面时将其删除,那么它不会破坏整个导航系统。
  • 是 VisualStateAwarePage 吗?如果是这样,您可能无法使用它,或者您可能需要创建自己的页面子类。

标签: c# mvvm windows-runtime windows-phone-8.1 prism


【解决方案1】:

这是可能的。这是解决方案(主要受this discussion启发):

创建一个允许视图模型禁用后退导航的界面:

public interface IRevertState
{
    bool CanRevertState();
    void RevertState();
}

在视图模型中实现接口:

public class myViewModel : ViewModel, IRevertState {
public bool CanRevertState() {
    return (...) //condition under which back navigation should be disabled
}
public void RevertState() {
    (...) // optionally reset condition if required
}

在 App.Xaml.cs 中处理后退导航:

#if WINDOWS_PHONE_APP
    protected override void OnHardwareButtonsBackPressed(object sender, BackPressedEventArgs e) {
        var page = (Page)((Frame)Window.Current.Content).Content;
        if (page.DataContext is IRevertState) {
            var revertable = (IRevertState)page.DataContext;
            if (revertable.CanRevertState()) {
                revertable.RevertState();
                e.Handled = true;
                return;
            }
        }
        base.OnHardwareButtonsBackPressed(sender, e);
    }
#endif

【讨论】:

    猜你喜欢
    • 2015-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多