WP7: Application Bar Click Event Problems

Working on my Windows Phone 7 application in Silverlight, I ran into a problem when the Click events on my Application Bar didn’t seem to fire.

Specifically, they don’t fire when calling out to one of the Chooser Tasks (photo in my case).

Apparently, there is a bug of some sort in the way controls are hooked up… when you return from a chooser, you are on a different thread than your normal UI thread. If you navigate to another page, then things get wacky and while the App Bar loads, it doesn’t hook up events.

The fix for this is in the Chooser Task completed event, use Dispatcher when making navigate calls…

Example (straight from my current source code):

    void photoChooserTask_Completed(object sender, PhotoResult e)
    {
        if (e.TaskResult == TaskResult.OK)
        {
            BitmapImage bitmap = new BitmapImage();
            bitmap.SetSource(e.ChosenPhoto);
            WriteableBitmap picLibraryImage = new WriteableBitmap(bitmap);
            (Application.Current as App).selectedPhoto = picLibraryImage;
            Dispatcher.BeginInvoke(() =>
                {
                    this.NavigationService.Navigate(new Uri("/PhotoEditPortrait.xaml", UriKind.Relative));
                });
        }
    }

And there you have it. It works perfectly for me. It would be nice if the framework did this automatically, since the App Bar isn’t really part of your UI, but oh well. This is how it is right now. If anyone knows of a better way to fix this