使用ObservableCollection异步填充ListView

时间:2014-07-15 20:29:50

标签: c# windows-phone async-await observablecollection windows-phone-8.1

所以,我在异步调用中填充集合,但我不知道为什么只有在异步方法完成后才能在ListView中显示项目。当项目被添加到ObservableCollection时,我希望它们逐渐出现。

public FilesPage()
{
    this.InitializeComponent();
    FilesViewModel = new FilesViewModel();
    DataContext = FilesViewModel;
}

protected override async void OnNavigatedTo(NavigationEventArgs e)
{
    //here I try to populate collection
    await FilesViewModel.FillWithData(e.Parameter == null ? "" : e.Parameter as String);
}

//inside FillWithData:
var progressIndicator = new Progress<StorageItemModel>(ReportProgress);
await PopulateItems(path, progressIndicator);

private async Task PopulateItems(string path,IProgress<StorageItemModel> progress)
{
    var folder = await StorageFolder.GetFolderFromPathAsync(path);
    IReadOnlyList<IStorageItem> readOnlyList = await folder.GetItemsAsync();
    foreach (var item in readOnlyList)
    {
        var model = await StorageItemModel.Create(item);
        progress.Report(model);
    }

}

我不知道为什么ListView没有收到有关集合更改的通知,因为我认为代码是在UI线程上执行的?或者不是吗? (Items的类型为ObservableCollection)

private void ReportProgress(StorageItemModel model)
{
    Items.Add(model);
}

0 个答案:

没有答案