如何取消任务?

时间:2016-08-20 07:42:17

标签: c# windows windows-phone-8.1 uwp

我在我的应用中覆盖BackButton并显示MessageDialog。

 public Scenario_3()
    {
        this.InitializeComponent();
        Windows.Phone.UI.Input.HardwareButtons.BackPressed += HardwareButtons_BackPressed;
    }


private async void HardwareButtons_BackPresseed(object sender, BackPressedEventArgs e)
    {
        e.Handled = true;
        var dialog = new MessageDialog("Do you want exit?");

        dialog.Commands.Add(new Windows.UI.Popups.UICommand("yes") { Id = 0 });
        dialog.Commands.Add(new Windows.UI.Popups.UICommand("no") { Id = 1 });

        dialog.DefaultCommandIndex = 0;
        dialog.CancelCommandIndex = 1;

        var result = await dialog.ShowAsync();

        if (result.Label == "yes")
        {
            this.Frame.Navigate(typeof(BlankPage1));

            ((Frame)Window.Current.Content).BackStack.Clear();
        }

enter image description here

导航到BlankPage1后,如果按BackButton,我再次看到MessageDialog。 导航后如何取消此覆盖?

1 个答案:

答案 0 :(得分:1)

根据您对我的评论的回复,当您离开该页面时,您似乎忘记取消订阅BackPressed事件。这样做将确保仅在您需要时调用事件处理程序。

例如:

private async void HardwareButtons_BackPresseed(object sender, BackPressedEventArgs e)
{
    e.Handled = true;
    var dialog = new MessageDialog("Do you want exit?");

    dialog.Commands.Add(new Windows.UI.Popups.UICommand("yes") { Id = 0 });
    dialog.Commands.Add(new Windows.UI.Popups.UICommand("no") { Id = 1 });

    dialog.DefaultCommandIndex = 0;
    dialog.CancelCommandIndex = 1;

    var result = await dialog.ShowAsync();

    if (result.Label == "yes")
    {
        // Leaving this page. Stop listening for Back button presses.
        Windows.Phone.UI.Input.HardwareButtons.BackPressed -= HardwareButtons_BackPressed;

        this.Frame.Navigate(typeof(BlankPage1));

        ((Frame)Window.Current.Content).BackStack.Clear();
    }