后退按钮运行Amok

时间:2015-11-05 14:41:46

标签: c# windows-10 uwp

在我的每个应用页面上,我都设置了后退按钮的功能,因为我希望每次都能执行不同的操作。但是,当我在一个页面上运行时:

SystemNavigationManager.GetForCurrentView().BackRequested += (s, a) =>
{
    Frame.Navigate(typeof(MainPage));
    a.Handled = true;
};

如果首先访问了该页面,它还会在我的另一个页面上运行后退按钮的功能。这会引发异常,因为它会尝试卸载不存在的项目。这不是每页设置后退按钮功能的正确方法吗?

1 个答案:

答案 0 :(得分:3)

这是正确的行为,因为SystemNavigationManager.GetForCurrentView()返回相同的SystemNavigationManager,因为它仍然是相同的视图(不是页面!),然后您有两个事件处理程序附加到事件。< / p>

如果您希望每页都有特定的事件处理程序,请使用OnNavigatedTo添加OnNavigatedFrom以删除事件处理程序:

public class BackButtonPage : Page
{
    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        BackButtonVisibility = base.Frame.CanGoBack ? AppViewBackButtonVisibility.Visible : AppViewBackButtonVisibility.Collapsed;

        SystemNavigationManager.GetForCurrentView().BackRequested += BackButtonPage_BackRequested;

        base.OnNavigatedTo(e);
    }

    protected override void OnNavigatedFrom(NavigationEventArgs e)
    {
        base.OnNavigatedFrom(e);

        SystemNavigationManager.GetForCurrentView().BackRequested -= BackButtonPage_BackRequested;
    }

    private void BackButtonPage_BackRequested(object sender, BackRequestedEventArgs e)
    {
        OnBackRequested(sender, e);
    }

    protected virtual void OnBackRequested(object sender, BackRequestedEventArgs e)
    {
        //your page specific code here
        Frame.Navigate(typeof(MainPage));
        e.Handled = true;
    }

    public AppViewBackButtonVisibility BackButtonVisibility
    {
        get { return SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility; }
        set { SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = value; }
    }
}

source from Microsoft's examples on github