我应该何时在 Windows Phone 8 应用程序中加载数据? [英] When should I load data in a Windows Phone 8 application?

查看:29
本文介绍了我应该何时在 Windows Phone 8 应用程序中加载数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里看到了很多与 OnNavigatedTo 方法相关的问题,但它们似乎都没有回答我应该在什么时候加载数据?"的基本问题.据我所知,MSDN 上的文档没有明确回答这个问题.

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.

如果我需要从本地数据库加载数据列表,使用哪种方法最合适?我应该使用 OnNavigatedTo 方法还是 Loaded 事件?

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;
   }
}

这意味着对于页面的新实例,同步加载数据.这也意味着在数据加载完成之前不会呈现页面,并且分析器抱怨我使用了太多的 UI 线程时间.

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;
   }
}

但是对于这种模式,在我看来,在我加载数据并设置 DataContext 之前,可能会发生导航,因此页面呈现可能会发生,这意味着不必要的重新绘制等等.

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.

推荐答案

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

I usualy bind to a ViewModel directly in XAML. Then in OnNavigatedTo I trigger the view model to fetch its data async.

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

This allows me to show basic values from start (page title etc.). Then when I start fetching the data I can also activate a progressbar directly in the ViewModel and then remove it once the data is fetched.

这篇关于我应该何时在 Windows Phone 8 应用程序中加载数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆