简体   繁体   中英

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. 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 ? 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 .

Task<ContentDialogResult> result = myContentDialog.ShowAsync();
//do something else here
await result;

How can I accomplish this?

IAsyncOperation works similar to Task . I was able to achieve this by awaiting IAsyncOperation and then using GetResults() to get the user response.

To replicate create a Button and TextBox named "MyTextBox" then paste below code in Button_Clicked event.

//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!";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM