1

I've seen a lot of questions here related to the OnNavigatedTo method, but none of them seem to answer the basic question of, "At what point should I load data?" The documentation on MSDN doesn't explicitly answer this question, as far as I can tell.

If I need to load a list of data from the local database, which method is the most appropriate to use? Should I use the OnNavigatedTo method, or the Loaded event?

What I've been using so far is this pattern, which seems to work well:

protected override void OnNavigatedTo(NavigationEventArgs e) {
   base.OnNavigatedTo(e);

   if (NavigationMode.New == e.NavigationMode) {
      var data = LoadData();
      this.DataContext = data;
   }
}

What this means is that for a new instance of a page, load the data synchronously. This also means that the page will not be rendered until the data has finished loading and the profiler complains that I'm using too much UI thread time.

An alternate approach is this pattern:

protected override async void OnNavigatedTo(NavigationEventArgs e) {
   base.OnNavigatedTo(e);

   if (NavigationMode.New == e.NavigationMode) {
      var data = await LoadData();
      this.DataContext = data;
   }
}

But with this pattern, it seems to me that navigation, and therefore page rendering may occur before I've loaded the data and set the DataContext, meaning unnecessary re-paints and what-not.

4

2 回答 2

3

我通常直接在 XAML 中绑定到 ViewModel。然后在 OnNavigatedTo 中触发视图模型以异步获取其数据。

这使我可以从一开始就显示基本值(页面标题等)。然后,当我开始获取数据时,我还可以直接在 ViewModel 中激活进度条,然后在获取数据后将其删除。

于 2013-05-16T06:31:19.913 回答
1

我建议您异步加载数据。OnNavigatedTo是您可以开始加载的地方。如果您谈论的是用户几乎肯定会导航到的页面,那么您可能能够更早地开始加载。

我有一系列博客文章,探讨了async与传统 OOP 的一些摩擦。有几篇文章特别关注数据绑定,例如异步构造(关于异步初始化的部分)和异步属性(关于数据绑定的部分)。

就在几个小时前,我宣布了我的 AsyncEx 库的第一个稳定版本,其中包括可用于启动异步加载操作并让视图在完成时自动响应(通过数据绑定)的NotifyTaskCompletion类型。

但回到核心问题:你必须在数据加载时显示一些东西。我建议您不要认为这是“不必要的”,而应将其视为提供更好用户体验的机会。想想你希望你的应用在速度较慢的手机上看起来像什么,或者加载数据时是否出错。任何时候有 I/O,设计“Loading...”和“Error”状态以及“Loaded”状态。

于 2013-05-15T18:56:17.167 回答