"Navigation is not allowed when the task is not in the foreground" in WP7 application
I m getting an error in WP 7.1 like below
InvalidOperationException "Navigation is not allowed when the task is not in the foreground"
In the following li开发者_高级运维ne of code
NavigationService.Navigate(new Uri("/PhotoPreview.xaml", UriKind.Relative));
I dont have any clue how to solve it. It would be great if you can provide some pointers
If you need to call it from the main UI thread, use this:
Dispatcher.BeginInvoke(() =>
{
NavigationService.Navigate(new Uri("/PhotoPreview.xaml", UriKind.Relative));
});
While using Dispatcher.BeginInvoke may help, it may well not fix your issue. I've also seen this occur if there is a race condition between 2 conflicting navigations, e.g. back key and forward navigation, or 2 forward navigations. See discussion on App Hub.
I'm reading between the lines here and assuming that you are using either the CameraCaptureTask or PhotoChooserTask due to the navigation string you are using "/PhotoPreview.xaml".
After battling with this issue myself I found that not only do you need to ensure that the navigation is called on the UI thread ( by using Dispatcher.BeginInvoke()
) but the CameraCaptureTask
object must be declared with class scope within the PhoneApplicationPage
class and you must call the chooser constructor and assign the Completed event delegate within the page’s constructor.
private readonly CameraCaptureTask cameraCaptureTask;
public MainPage()
{
cameraCaptureTask = new CameraCaptureTask();
cameraCaptureTask.Completed += CameraCaptureCompleted;
}
otherwise your application will be deactivated in the background and will never recieve the photo. Causing the application to crash with one of the following exceptions:
- Navigation is not allowed when the task is not in the foreground
- 0x8000ffff
- Navigation is not allowed after the task has been canceled. Error: -2147220992
- Navigation is not allowed when the task is not in the foreground. Error: -2147220990
Some further tips:
Don't remove the event handler in your CameraCaptureCompleted
method either or it won't work the next time around!
You may also want to add some code to ensure that navigation can't occur twice due to multiple button clicks for example; the touch screens can be quite sensitive! If you are only using the capture task, a try catch block around the Show() call to trap an InvalidOperationException
should be fine.
tl;dr
Only assign the CameraCaptureTask/PhotoChooser and it's event handler in your page constructor.
精彩评论