我想显示图片库中的图片。我获取图片并绑定数据。
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;
这是设置 BitmapImage 的 getImage()。
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;
}
但图片不显示。我认为这是因为异步功能,但我不知道解决方案。你可以帮帮我吗 ?
我不确定你如何使用设置为的数据DefaultViewModel
,但是,是的,看起来像async
方法是你的问题。
你需要做的是以某种方式await
每次致电getImage()
。一种方法是使用async
拉姆达在你的select
。但要做到这一点,您需要使用方法语法。
当你这样做时,你将拥有IEnumerable<Task<a>>
(where a
是你的匿名类型),但你只需要IEnumerable<a>
。为此,请使用Task.WhenAll() http://msdn.microsoft.com/en-us/library/hh194766.aspx(这将返回Task<a[]>
) 进而await
其结果:
var tasks = myPictures.Select(
async file => new { Subtitle = "subtitle", Title = "title", Image = await getImage(file.Path) });
var data = await Task.WhenAll(tasks);
这将执行所有getImage()
一次,这可能不是最有效的解决方案。如果您不希望这样,则需要不同的解决方案。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)