[英]How to process while waiting for user input from ContentDialog
With asynchronous tasks I often postpone await
to perform other processing while waiting for async task to return.对于异步任务,我经常推迟
await
执行其他处理,同时等待异步任务返回。 For example, instead of:例如,而不是:
bool t = await myAsync();
I use我用
Task<bool> t = myAsync();
//do something else here while waiting
await t; //or await Task.WhenAll(t, p, s); when more than one
How can I use this approach with ContentDialog
?如何将这种方法与
ContentDialog
? I want to display content dialog to the user and perform other processing while the user waits to respond.我想向用户显示内容对话框并在用户等待响应时执行其他处理。
I tried below approach but that fails because ContentDialog
returns IAsyncOperation
instead of a Task
.我尝试了以下方法,但失败了,因为
ContentDialog
返回IAsyncOperation
而不是Task
。
Task<ContentDialogResult> result = myContentDialog.ShowAsync();
//do something else here
await result;
How can I accomplish this?我怎样才能做到这一点?
IAsyncOperation
works similar to Task
. IAsyncOperation
工作方式类似于Task
。 I was able to achieve this by awaiting IAsyncOperation
and then using GetResults()
to get the user response.我能够通过等待
IAsyncOperation
然后使用GetResults()
来获取用户响应来实现这一点。
To replicate create a Button
and TextBox
named "MyTextBox" then paste below code in Button_Clicked
event.要复制创建一个名为“MyTextBox”的
Button
和TextBox
然后将下面的代码粘贴到Button_Clicked
事件中。
//prep dialog
ContentDialog dialog = new ContentDialog
{
Content = "Test Dialog",
Title = "Test Dialog",
SecondaryButtonText = "Cancel",
PrimaryButtonText = "OK"
};
//show dialog
IAsyncOperation<ContentDialogResult> result = dialog.ShowAsync();
//do some background processing
MyTextBlock.Text = "background processing...";
//wait for user response
_ = await result;
//get user response
ContentDialogResult buttonClicked = result.GetResults();
//display user response on screen
if(buttonClicked != ContentDialogResult.Primary)
{
MyTextBlock.Text += "\nYou cancelled!";
}
else
{
MyTextBlock.Text += "\nYou pressed OK!";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.