Michael Crump bio photo

Michael Crump

Works @Microsoft on Windows

Twitter Google+ LinkedIn Github Youtube Flickr

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.

image

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:

image

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?

image

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.

SNAGHTML84aa445

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"));              break;          case 1:              Deployment.Current.Dispatcher.BeginInvoke(() => ShowMe("Baseball"));              break;          default:              break;      }  }    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.

image

 

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

alt Subscribe to my feed