ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

Chooser.ShowAsync()

Show Windows Phone Choosers using the async/await pattern instead of using the completed event.

Source

public static Task<T> ShowAsync<T>(this ChooserBase<T> chooser)
    where T : TaskEventArgs {

    TaskCompletionSource<T> tcs = new TaskCompletionSource<T>();

    EventHandler<T> handler = null;

    handler = (s, e) => {
        chooser.Completed -= handler;

        if (e.Error != null)
            tcs.SetException(e.Error);
        else
            tcs.SetResult(e);
    };

    chooser.Completed += handler;
    chooser.Show();

    return tcs.Task;
}

Example

private async void Button_Click(object sender, RoutedEventArgs e) {
    try {
        var c = new PhotoChooserTask();
        var result = await c.ShowAsync();
        var bi = new BitmapImage();
        bi.SetSource(result.ChosenPhoto);
        imagePhoto.Source = bi;
    } catch (Exception ex) {
        MessageBox.Show(ex.Message);
    }
}

Author: Fons Sonnemans

Submitted on: 23 okt. 2013

Language: C#

Type: Microsoft.Phone.Tasks.ChooserBase<T>

Views: 5664