Search code examples
windows-phone-7listboxselectionchanged

Windows Phone 7 Selection_Changed automatically


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?


Solution

  • 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.