In winrt XAML toolkit, we found the framework asyncui in another codeplex. It is very interesting. You can use the async/await feature of C #5.0 to wait for events on the interface.
For example, the name of a button on the page is BTN, which can be written in the loaded event of the page.
// + Using winrtxamltoolkit. asyncui;
// The main_loaded_1 is the page loaded event.
// There is a button named BTN on the main interface
Private async void main_loaded_1 (Object sender, routedeventargs E)
{
// Return a task using the buttonextensions. waitforclickasync method <routedeventargs>
VaR ARGs = await BTN. waitforclickasync ();
// Wait for code asynchronously after click execution
Show ("button clicked:" + args. originalsource );
}
// Display messagedialog
Static async void show (string S)
{
Await new messagedialog (s). showasync ();
}
The Code uses the buttonextensions. waitforclickasync method in asyncui to asynchronously wait for the returned task <routedeventargs> object through await, so as to asynchronously wait for the Click Event of the button. When a button is clicked, the corresponding event is executed! For example:
The principle is to use the eventasync. fromroutedevent method in asyncui. This method returns the task attribute of another type of routedeventhandlertasksource. This type uses the eventasync. fromroutedevent parameter to display and register the target event and cancel the registration. The following is the source code of the buttonextensions. waitforclickasync method:
Public static async task <routedeventargs> waitforclickasync (this buttonbase button)
{
Return await eventasync. fromroutedevent (
Eh => button. Click + = eh,
Eh => button. Click-= EH );
}
Finally, routedeventhandlertasksource uses taskcompletionsource in. Net to set the result of the corresponding UI event to taskcompletionsource, and returns routedeventargs as the returned result of the task. After the task is completed, the code for canceling event registration in the eventasync. fromroutedevent method is run.