以编程方式关闭 MessageDialog [英] Programmatically dismiss a MessageDialog

查看:25
本文介绍了以编程方式关闭 MessageDialog的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Windows Phone 8.1 上,如何在 ShowAsync 调用后以编程方式关闭 MessageDialog?

On Windows Phone 8.1, how to programmatically dismiss a MessageDialog after the ShowAsync call?

我尝试调用 IAsyncInfo.Close(),它只是抛出一个 InvalidOperationException 请求了非法状态更改".

I’ve tried calling IAsyncInfo.Close(), it just throws an InvalidOperationException "An illegal state change was requested".

我试过调用 IAsyncInfo.Cancel().对话框保持可见,这是唯一的结果 - 在我点击关闭"按钮后,TaskCancelledException 被封送到等待程序中.

I’ve tried calling IAsyncInfo.Cancel(). The dialog stays visible, the only result - after I tap the "Close" button, TaskCancelledException is marshaled to the awaiting routine.

更新:确切的行为取决于调用的顺序.

Update: exact behavior depends on the sequence of the calls.

  1. 如果在 await theTask 之前调用 IAsyncOperation.Cancel() - await 关键字立即抛出 TaskCancelledException.但是,对话框保持可见.
  2. 如果 await theTask;IAsyncOperation.Cancel() 之前被调用,对话框保持可见,但与 #1 不同的是,await 继续等待用于点击按钮.只有这样才会引发 TaskCanceledException.
  1. If IAsyncOperation.Cancel() is invoked before await theTask - await keyword throws TaskCancelledException at once. However, the dialog stays visible.
  2. If await theTask; is invoked before IAsyncOperation.Cancel(), the dialog stays visible, but unlike #1, await continues waiting for a button to be tapped. Only then a TaskCanceledException is raised.

顺便说一句,我的场景是 #2:我需要能够在某个例程已经等待完成后关闭消息对话框.

BTW, my scenario is #2: I need to be able to close message dialogs after some routine is already waiting for its completion.

推荐答案

这是在 RT 中完成的方式.保存该 ShowAsync 任务,您可以稍后取消该任务.

This is how it's done in RT. Save that ShowAsync Task and you can cancel that later.

    private IAsyncOperation<IUICommand> dialogTask;
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        MessageDialog dlg = new MessageDialog("This will close after 5 seconds");
        try
        {
            dialogTask = dlg.ShowAsync();
        }
        catch (TaskCanceledException)
        {
            //this was cancelled
        }

        DispatcherTimer dt = new DispatcherTimer();
        dt.Interval = TimeSpan.FromSeconds(5);
        dt.Tick += dt_Tick;
        dt.Start();
    }

    void dt_Tick(object sender, object e)
    {
        (sender as DispatcherTimer).Stop();
        dialogTask.Cancel();
    }

注意 ShowAsync() 不是等待的.而是保存到可以取消的任务中.可悲的是,我在 WP 上尝试过这个,但没有奏效.

Notice the ShowAsync() is not awaited. Instead is saved to a task which can be cancelled. Sadly I tried this on WP and it didn't work.

这篇关于以编程方式关闭 MessageDialog的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆