I just finished a knock-down drag-out battle against my own code. And I won. Finally.
Quite frankly, this was completely unexpected behavior, and I wasn’t sure if it was native behavior or introduced by something I did, or something that the Non-Linear Navigation Service provided by Yochay Kiriaty caused, but it turns out to be native behavior. I’ll explain the problem, then show how I overcame it.
Non-Linear Navigation Service
But first of all I want to emit a word or two in praise of Yochay Kiriaty and the Windows Phone Developer team for their work creating the Non-Linear Navigation Service! Hip hip hooray! The Ham Radio Practice Exam app is complex enough to be getting into some serious loop navigation problems and I was starting to despair that I would have to interrupt development in order to fix the problem myself. But then I happened upon NLNS, and my problem was solved! I am most grateful, and this ought to demonstrate the dedication and attention to detail put forth by Microsoft’s Windows Phone Developement Team. This is one classy bunch!
Navigation Using a List Box
Rather than trying to work inside my app, which in the relevant locations has a lot of code unnecessary to illustrate the problem, I’ll use a bare-bones example. Let’s start with the list box:
Here is its SelectionChanged handler:
Page1.xaml is a simple page with nothing in particular on it. The interesting behavior is demonstrated by running the app. Click on either of the two list box items, and you will be taken to Page1. Everything very normal and boring. But now click on the Back navigation button. You find yourself back on the MainPage looking at the List Box, as expected, but there’s a difference. See the color of the List Item you clicked earlier? It’s a blue color and if you click on it now, nothing happens. If you click on the other List Item, you will be taken to Page1, and upon return to the MainPage this time the other List Item will be blue and unselectable.
I had this problem, so all you do is under the line of code that navigates you to the page your after, you set the Selected Index to -1
See the below for my implementation.
private void FirstListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// if an item is selected
if (MainMenuListBox.SelectedIndex == 1) // quick search
{
NavigationService.Navigate(new Uri(“/QuickSearch.xaml”, UriKind.Relative));
MainMenuListBox.SelectedIndex = -1; // Clear the Selection Index
}
// if an item is selected
if (MainMenuListBox.SelectedIndex == 3) // about page
{
NavigationService.Navigate(new Uri(“/AboutPage.xaml”, UriKind.Relative));
MainMenuListBox.SelectedIndex = -1; // Clear the Selection Index
}
}
Nice!
Yup, did the same thing as i ran into the same issue:
MyListBox.SelectedIndex = -1