Friday, December 16, 2011

OnNavigatedTo will be called after selecting a date using DatePicker

Long Story:
During developing my Windows Phone application I faced a strange problem. At first I thought that the problems is related to DatePicker Value binding is not working properly. I tried several things and then finally I relaized that OnNavigatedTo method is being called when the user selects a data or presses the back button and then when this method is executed again I override all the bindings. And the solution is very simple, just check for NavigationMode of event args to not be NavigationMode.Back, here is a sample code:

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
    base.OnNavigatedTo(e);
 
    if (e.NavigationMode == System.Windows.Navigation.NavigationMode.Back)
        return;
 
    viewModel = new AddWeightViewModel();
    viewModel.Date = DateTime.Today;
 
    this.DataContext = viewModel;
}


Short Story:
Always make sure that you add the following lines of code to the OnNavigatedTo method, specially if you have a DatePicker on your page:

    if (e.NavigationMode == System.Windows.Navigation.NavigationMode.Back)
        return;

By adding the above code to the beginning of OnNavigatedTo you prevent from resetting your page data. Keep in mind although the OnNavigatedTo is called, the page is still has its own values.








3 comments:

  1. You'll have to keep in mind what code gets run in the case where you've been tombstoned. Consider what happens if you navigate beyond this page, leave the app and allow it to become tombstoned, then return to where you left off and hit Back to return to this page.

    You may want some of your OnNavigatedTo code to be run again even though it's being loaded through a Navigate Back because your old instance of the page doesn't exist anymore. In this example specifically you'll want to at least set your DataContext again or none of your databound UI will display after the tombstone.

    ReplyDelete
  2. Agreed. Actually my point was about the simple fact that DatePicker uses navigation and OnNavigateTo will be called. But as you said the given code is not complete regarding to tombstoning concerns.

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete