Reloading MainPage in WP7 to restart the app
My app only has one page - the MainPage. When the user selects "new" f开发者_如何转开发rom the ApplicationBar Menu all I really want to do is clear my source data and reload the page.
Can I do this with NavigationService? The following line gets a Navigation Failed exception in the RootFrame of the App when called from within the MainPage itself:
this.NavigationService.Navigate(new Uri("MainPage.xaml", UriKind.Relative));
Can this be done so easily, or do I need to create a second page to navigate to before navigating back to my MainPage?
Using navigation for this purpose sounds like a horrible way of doing it! If you create a second page as a workaround to the problem you are facing, it will remain on the back-stack, meaning that it will be reachable when the user hits the back button.
I would recommend adopting the MVVM pattern (see the example here). When the new button is pressed, simply create a new view model and associate it with your MainPage
by setting it as the DataContext
, this will have the affect you desire of clearing and resetting the state.
It turns out there was a typo in the code:
this.NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
The slash in front of MainPage.xaml corrected the Navigation Failed exception I mentioned.
And, of course, this didn't help at all for reloading the page as if the app had just launched, nor did navigating away and returning. Clearing the data and refreshing the UI was trivial and the correct thing to do (MVVM was not required, though it would be an improvement).
Thanks ColinE for the link and the nudge in the right direction.
精彩评论