by brad
1. October 2010 15:04
The next couple of tips will examine three possible hooks that you can use to execute code when a Windows Phone 7 page “starts”: The constructor, the Loaded event, and the OnNavigatedTo method. These three guys have a lot of similarities but it’s important to understand their differences. We’ll start with the constructor.
Constructor
1: public partial class MainPage : PhoneApplicationPage
2: {
3: public MainPage()
4: {
5: InitializeComponent();
6: }
7: }
The constructor for your page is a C# concept of course, not a Windows Phone 7 concept. Your pages are C# objects and like any object, the constructor is called once and only once for each object when it is instantiated. So it follows that code that initializes your pages should go here, which is why you’ll see a call to InitializeComponent already there. InitializeComponent contains the generated code that executes to set up the page before its first use. Other initialization code, like setting up dependencies, should go in your constructor. You could also initialize any ViewModels in the constructor but be aware of when the constructor will be called and when it will not be called.
When it’s called and when it’s not
The constructor is called when a new instance of a page is created. Windows Phone will create a new instance of the startup page when the application launches. Other pages are created when they are navigated to by passing in a new Uri to the navigation service.
1: NavigationService.Navigate(new Uri("/Views/ListPage.xaml", UriKind.Relative));
The code above will result in a new instance of ListPage being created and the constructor for that page will be called. After ListPage page has been created, it will be navigated to.
A new instance of a page is not created, and the constructor is not called, when the user navigates to a page by using the Back button, or the user is navigated backwards or forwards using the NavigationService. In these cases, the existing page will be navigated to and no new pages are created.
Update: As Daniel pointed out in the comments, the constructor will be called if your application has been tombstoned and the Back button is used to return to it. This makes sense, since the object that is your page will have been disposed of when the application was tombstoned.
1: NavigationService.GoBack()
The code above will re-use the already existing page and the constructor will not be called.
Summary
- The constructor is called when a new instance of your page is created.
- Just like with any C# class, code that initializes your class (gets the class ready to do its work) belongs here.
- The constructor will be called when a page is navigated to by passing in a new Uri to the navigation service
- The constructor will not be called when the user uses the Back button or the GoBack() methods of the navigation service are used.
Other Resources
More Tips