Pages

Showing posts with label DatePicker. Show all posts
Showing posts with label DatePicker. Show all posts

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.