繁体   English   中英

使用MVVM Light在WP Universal App上异步加载数据

[英]Loading data asynchronously on WP Universal App using MVVM Light

我正在使用MVVM Light开发Windows Phone通用应用程序(我是MVVM模式的新手)。 我的问题是使它像这样工作:

  1. 启动应用程序(或用户导航到其他视图),
  2. 然后我们看到基本的用户界面,
  3. 然后我们等待数据加载,而应用程序保持响应状态。

到目前为止,我已经测试了许多不同的方法,例如:

并且在每种情况下, 除非加载了数据,否则我的应用程序都显示初始屏幕(或在导航到另一页之前被阻止)。 该方法正确返回数据,视图显示良好。

所以我的问题是, 在Universal App中异步加载数据的正确方法什么? 感谢您的帮助。

这是我的代码现在的样子:

    public MainViewModel()
    {
        this._navigationService = ServiceLocator.Current.GetInstance<INavigationService>();

        _newsService = ServiceLocator.Current.GetInstance<INewsService>();

        LoadMainPageCommand =
            new RelayCommand(async() => await LoadMainPageData());
    }

    public RelayCommand LoadMainPageCommand { get; set; }

    private async Task LoadMainPageData()
    {
        // to make it work a bit longer
        for (int i = Int32.MaxValue; i > 20000; i--) ;

        NewsCategories= await _newsService.GetNewsCategoriesAsync();
        RaisePropertyChanged("NewsCategories");
    }

<Page
x:Class="xxx.HubPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:xxx"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"    
xmlns:i="using:Microsoft.Xaml.Interactivity"
xmlns:core="using:Microsoft.Xaml.Interactions.Core"
xmlns:data="using:xxx.Data"
mc:Ignorable="d">
<i:Interaction.Behaviors>
    <core:EventTriggerBehavior EventName="Loaded">
        <core:InvokeCommandAction Command="{Binding LoadMainPageCommand}"/>
    </core:EventTriggerBehavior>
</i:Interaction.Behaviors>
...

public interface INewsService
{
    Task<ObservableCollection<NewsCategory>> GetNewsCategoriesAsync();
}

您的问题出在您的“测试”代码中:

private async Task LoadMainPageData()
{
  // to make it work a bit longer
  for (int i = Int32.MaxValue; i > 20000; i--) ;

  NewsCategories= await _newsService.GetNewsCategoriesAsync();
  RaisePropertyChanged("NewsCategories");
}

这是一种具有异步签名的方法,正在执行同步工作。 如果要延迟,请异步执行:

private async Task LoadMainPageData()
{
  // to make it work a bit longer
  await Task.Delay(TimeSpan.FromSeconds(3));

  NewsCategories= await _newsService.GetNewsCategoriesAsync();
  RaisePropertyChanged("NewsCategories");
}

那么任何一种方法都应该起作用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM