开发者

When to Call ViewModel.LoadData?

I have a WP7 Silverlight app that displays a bunch of data using Pivot. When first creating the project, the Visual Studio template calls V开发者_StackOverflow中文版iewModel.LoadData in Page_Loaded:

private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
    App.ViewModel.LoadData();
}

However on MSDN it says you should use OnNavigatedTo instead of Page_Loaded, because OnNavigatedTo is called only once when a page becomes active, while Page_Loaded is called everytime an item is added to the page's visual tree. The MSDN article is for Silverlight 4 instead of for Silverlight Windows Phone though.

You override the OnNavigatedTo method to examine the navigation request and prepare the page for display. For example, you can load the requested data and enable or disable visual elements.

Typically, you use the OnNavigatedTo method instead of creating an event handler for the Loaded event. The OnNavigatedTo method is preferable because it is only called once for each time the page becomes active. The Silverlight framework raises the Loaded event each time the element is added to the visual tree, which potentially can happen more than once when activating a page. The OnNavigatedTo method is called for each request, even when the page is retrieved from the cache. You should include in this method code that must be executed for each request rather than placing that code in the Page constructor.

Is there any reason why the Visual Studio Pivot template calls ViewModel.LoadData in Page_Loaded?


I think you're confusing LayoutUpdated and Loaded.
Loaded should only get called once each time the page is displayed.

Loading data specific to a page after that page has been constructed is a simple way of working with data tied to a specific page. My guess is that the default templates use this as it's simple to understand and learn from.

Update
The article in MSDN that you refer to is for Page.Loaded. WP7 does not use Page instead it uses PhoneApplicationpage.
Having worked with WP7 for over a year and created dozens of apps, I've never seen the Loaded event called multiple times in a WP7 app.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜