Visually Located

XAML and GIS

Making the Windows Phone Toolkit CustomMessageBox async

The Windows Phone Toolkit has a nice CustomMessageBox control that allows you to customize the button text of a MessageBox. This message box is nice but you must subscribe to an event for when it is closed.

Microsoft.Phone.Controls.CustomMessageBox msgBox = new CustomMessageBox();
msgBox.RightButtonContent = "cancel";
msgBox.LeftButtonContent = "delete";
msgBox.Caption = "Are you sure you want to delete?";
msgBox.Title = "Delete message?";
msgBox.Dismissed += (o, eventArgs) =>
    {
        // Do some logic in here.
    };
msgBox.Show();

This requires that your logic for user input to be either in a separate method or above the Show method like in my example. If the CustomMessageBox had a way to show it asynchronously, you could have your logic in one place. Luckily this is very easy with an extension method.

public static class ToolkitExtensions
{
    public static Task<CustomMessageBoxResult> ShowAsync(this CustomMessageBox source)
    {
        var completion = new TaskCompletionSource<CustomMessageBoxResult>();
        
        // wire up the event that will be used as the result of this method
        EventHandler<DismissedEventArgs> dismissed = null;
        dismissed += (sender, args) =>
            {
                completion.SetResult(args.Result);
                
                // make sure we unsubscribe from this!
                source.Dismissed -= dismissed;
            };
 
        source.Show();
        return completion.Task;
    }
}

This new extension method allows your code to flow better.

Microsoft.Phone.Controls.CustomMessageBox msgBox = new CustomMessageBox();
msgBox.RightButtonContent = "cancel";
msgBox.LeftButtonContent = "delete";
msgBox.Caption = "Are you sure you want to delete?";
msgBox.Title = "Delete message?";
var result = await msgBox.ShowAsync();
// Do something with result

NOTE:  If you are developing a Windows Phone 7 application, you will need the async BCL from nuget

blog comments powered by Disqus