【问题标题】:Doing something when user click the BackButton当用户单击 BackButton 时做某事
【发布时间】:2015-12-18 01:38:40
【问题描述】:

当用户单击手机上的硬件按钮时,我想做一些事情。我有两页。在 App.xaml.cs 中,我添加了以下代码来处理页面之间的导航。

SystemNavigationManager.GetForCurrentView().BackRequested += OnBackRequested;

private void OnBackRequested(object sender, BackRequestedEventArgs e)
{
    if (this.Frame.CanGoBack)
        this.Frame.GoBack();
}

但是现在当用户单击后退按钮时,我想做其他事情。我该怎么做?

【问题讨论】:

  • 不确定你想要什么,但你只需要替换“if (this.Frame.CanGoBack) this.Frame.GoBack();”并在那里设置你的代码。当您单击后退按钮时,将始终调用 OnBackRequested。
  • 我可以这样做,但我需要在我的应用程序的每个页面上做不同的事情

标签: c# visual-studio-2015 uwp windows-10-mobile


【解决方案1】:

如果您希望后退按钮在每个页面上执行不同的操作,那么您将需要处理每个页面上的后退按钮 - 我这样做是为了提示用户确认在我的一个页面上丢失他们的更改。

在每个页面的 OnNavigatedTo 方法中订阅 BackRequested 事件:

protected override void OnNavigatedTo(Windows.UI.Xaml.Navigation.NavigationEventArgs e)
{
    SystemNavigationManager.GetForCurrentView().BackRequested += this.OnBackPressed;
    base.OnNavigatedTo(e);
}

并确保在页面的 OnNavigatedFrom 方法中取消订阅:

protected override void OnNavigatingFrom(Windows.UI.Xaml.Navigation.NavigatingCancelEventArgs e)
{
    SystemNavigationManager.GetForCurrentView().BackRequested -= this.OnBackPressed;
    base.OnNavigatingFrom(e);
}

现在您可以在每个页面上编写一个 OnBackPressed() 事件处理程序来执行您希望它在该页面上执行的操作。

【讨论】:

    【解决方案2】:

    如果您的意思是在返回之前运行某个方法来“做某事”,您可以为此使用Page 导航方法

    OnNavigatingFrom 表示“在页面卸载之前立即调用并且不再是父框架的当前源。”

    OnNavigatinTo 表示“在页面加载并成为父框架的当前源时调用。”

    OnNavigatedFrom 表示“在页面卸载后立即调用并且不再是父框架的当前源。”

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        string productID;
        DataServiceContext svcContext = 
            new DataServiceContext(new Uri("AdventureWorks.svc", UriKind.Relative));
    
        if (this.NavigationContext.QueryString.ContainsKey("ProductId"))
        {
            productID = this.NavigationContext.QueryString["ProductId"];
        }
        else
        {
            productID = App.Current.Resources["FeaturedProductID"].ToString();
        }
    
        svcContext.BeginExecute<Product>(new Uri("Product(" + productID + ")", 
            UriKind.Relative), loadProductCallback, svcContext);
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多