I want to display pictures in the Pictures library. I get pictures and bind data.
StorageFolder picturesFolder = KnownFolders.PicturesLibrary;
IReadOnlyList<StorageFile> myPictures = await picturesFolder.GetFilesAsync();
var mydata = from file in myPictures select new { Subtitle = "subtitle", Title = "title", Image = this.getImage(file.Path) };
this.DefaultViewModel["Items"] = mydata;
This is getImage() for set BitmapImage.
private async Task<BitmapImage> getImage(string finename)
{
StorageFolder picturesFolder = KnownFolders.PicturesLibrary;
StorageFile file = await picturesFolder.GetFileAsync(fileName);
var stream = await file.OpenReadAsync();
var bitmap = new BitmapImage();
bitmap.SetSource(stream);
return bitmap;
}
But pictures are not displayed.I think this is because of async function, but I don't know the solution. Could you help me ?
I'm not sure how do you use the data that set to
DefaultViewModel
, but yeah, it looks like theasync
method is your problem.What you need to do is to somehow
await
each call togetImage()
. One way to do this is to useasync
lambda in yourselect
. But to do that, you need to use the method syntax.When you do that, you will have
IEnumerable<Task<a>>
(wherea
is your anonymous type), but you need justIEnumerable<a>
. To get that, useTask.WhenAll()
(which will returnTask<a[]>
) and thenawait
its result:This will execute all
getImage()
s at once, which may not be the most efficient solution. If you don't want that, you would need different solution.svick's solution seems like should work, but as he/she said - it might not be the most efficient solution. A better solution for a folder with unknown number of files is to use data virtualization with
FileInformationFactory.GetVirtualizedFilesVector()
. That works best with a converter.Something I have used:
Getting a virtualized file list and binding to a ListView
XAML
IStorageItemInformationToBitmapImageConverter