Windows Phone 7 Selection_Changed automatically

499 views Asked by At

currently I'm developing an app for WP7 but came across a little problem with a Listbox event call Selection_Change. The problem is that when i return to the page that contains the listbox the selection_change event triggers without being changed at all or without any user input. The listbox code is similar to this:

private void lsbHistory_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    int index = lsbHistory.SelectedIndex;
    NavigationService.Navigate(new Uri("/Views/NextPage, UriKind.Relative));
}

On the page I navigate to, the only way out of the navigated page is by pressing back button or start button meaning that it will return to the page that contains the listbox. When I Navigate back the selection change triggers leading me sometimes to a exception. Has anyone been through this before?

3

There are 3 answers

3
Claus Jørgensen On BEST ANSWER

Consider always checking if it's -1 (the default value).

private void lsbHistory_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    int index = lsbHistory.SelectedIndex;
    if (index != -1)
    {
        NavigationService.Navigate(new Uri("/Views/NextPage, UriKind.Relative));
        lsbHistory.SelectedIndex = -1; // Set it to -1, to enable re-selection.   
    }
}

Also, you should consider wrapping the Navigate call in Dispatcher.BeginInvoke to have a better, more smooth, page transition.

0
Matt Lacey On

The event will be fired when the list is populated.

The simplest solution for you will probably be to add a check that there is nothing selected before triggering your navigation:

if (lsbHistory.SelectedIndex > -1)
{
    // do navigation
}
1
Mikael Koskinen On

One thing to notice is that when you navigate back to the page which containt the ListBox, the ListBox still has the SelectedItem set to the value it had when the user navigated away. This means that lsbHistory.SelectedIndex will get the index of the item which was selected when the user navigated forward.

Maybe there's something in your code which presumes that the ListBox's SelectedItem is null when the user navigates to the page?