Over a million developers have joined DZone.

Building a better MessageBox for WP7 with the help of XNA

· Mobile Zone

I’ve recently had the requirement to allow my user to choose between two items in my Windows Phone 7 application. The first way that I thought of tackling this was using the standard MessageBox.Show that is included with the System.Windows class and seeing if the enum provided a way to allow custom text.


Unfortunately, it did not. As you can see from the image above, it only includes an OK and an OKCancel. If we run this application, then we get the following:


Kinda boring and doesn’t allow any real customization. But, what if we wanted to display custom text where the ok and cancel buttons are? What if we wanted our application to look like the following?


This is where we could use a little help from XNA libraries.

Go ahead and open your Windows Phone 7 Project and right click on References and select Microsoft.Xna.Framework.GamerServices as shown below.


Now that we have access to the proper library, go ahead and add a button and add the following code snippet. (assuming you name it button1 and wired up the event handler).

private void button1_Click(object sender, RoutedEventArgs e)
    Guide.BeginShowMessageBox("Sport", "Which sport do you prefer?", new string[] { "Football", "Baseball" }, 1, MessageBoxIcon.None,
                              new AsyncCallback(OnMessageBoxClosed), null);
private void OnMessageBoxClosed(IAsyncResult ar)
    int? buttonIndex = Guide.EndShowMessageBox(ar);
    switch (buttonIndex)
        case 0:
            Deployment.Current.Dispatcher.BeginInvoke(() => ShowMe("Football"));
        case 1:
            Deployment.Current.Dispatcher.BeginInvoke(() => ShowMe("Baseball"));
public void ShowMe(string title)
    PageTitle.Text = title;

In this example, I added a Button and am simply changing the PageTitle.Text to be whatever you selected. As you can see this code is pretty simple, and the only thing you may be confused about is the Deployment.Current.Dispatcher.BeginInvoke() call. The reason that this is in here is because without it is is an Invalid cross-thread access as shown below.



Thanks again for reading and hopefully this bails someone out like it did for me.


Published at DZone with permission of Michael Crump. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}