[英]Loading data asynchronously on WP Universal App using MVVM Light
我正在使用MVVM Light開發Windows Phone通用應用程序(我是MVVM模式的新手)。 我的問題是使它像這樣工作:
到目前為止,我已經測試了許多不同的方法,例如:
並且在每種情況下, 除非加載了數據,否則我的應用程序都顯示初始屏幕(或在導航到另一頁之前被阻止)。 該方法正確返回數據,視圖顯示良好。
所以我的問題是, 在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.