Visually Located

XAML and GIS

Avoid InvalidOperationException when navigating in your Windows Phone apps

I have no idea how I get this error, but in every app I’ve published I get error reports in which navigation fails and throws an InvalidOperationException. The entire stack trace is similar to

System.InvalidOperationException
Navigation is not allowed when the task is not in the foreground.
   at System.Windows.Navigation.NavigationService.Navigate(Uri source)
   at MyWPApp.MainPage.OnListBoxItemSelected(Object sender, SelectionChangedEventArgs e)
   at System.Windows.Controls.Primitives.Selector.OnSelectionChanged(SelectionChangedEventArgs e)
   at System.Windows.Controls.Primitives.Selector.InvokeSelectionChanged(List`1 unselectedItems, List`1 selectedItems)
   at System.Windows.Controls.Primitives.Selector.SelectionChanger.End()
   at System.Windows.Controls.Primitives.Selector.SelectionChanger.SelectJustThisItem(Int32 oldIndex, Int32 newIndex)
   at System.Windows.Controls.ListBox.MakeSingleSelection(Int32 index)
   at System.Windows.Controls.ListBox.HandleItemSelection(ListBoxItem item, Boolean isMouseSelection)
   at System.Windows.Controls.ListBox.OnListBoxItemClicked(ListBoxItem item)
   at System.Windows.Controls.ListBoxItem.OnManipulationCompleted(ManipulationCompletedEventArgs e)
   at System.Windows.Controls.Control.OnManipulationCompleted(Control ctrl, EventArgs e)

As you can see the error states “Navigation is not allowed when the task is not in the foreground” yet everything about this stack trace indicates that the event and call to Navigate IS in the foreground.

Instead of trying to figure out how or why this occurs, I decided to create a new NavigateToPage extension method that ignores this exception.

public static class Extensions
{
    public static bool NavigateToPage(this NavigationService source, string uri)
    {
        try
        {
            return source.Navigate(new Uri(uri, UriKind.Relative));
        }
        catch (InvalidOperationException)
        {
            return false;
        }
    }
}

I also took the liberty of not requiring a Uri as I hate having to add the UriKind every time. Now everywhere in my app I use the new NavigateToPage method.

NavigationService.NavigateToPage("/SecondPage.xaml");
blog comments powered by Disqus