如何显示从图片目录图像? [英] How to display images from Picture Directory ?
问题描述
我要显示在图片库的图片。我得到的图片和数据绑定。
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;
这是的getImage()进行设置的BitmapImage。
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;
}
但图片不displayed.I认为这是因为异步函数,但我不知道解决的办法。你能帮助我吗?
But pictures are not displayed.I think this is because of async function, but I don't know the solution. Could you help me ?
推荐答案
我不知道你怎么使用设置为 DefaultViewModel
中的数据,但是,是的,它看起来像异步
方法是你的问题。
I'm not sure how do you use the data that set to DefaultViewModel
, but yeah, it looks like the async
method is your problem.
您需要做的就是以某种方式等待
每次调用的getImage()
。这样做的一个方法是使用异步
拉姆达在选择
。但要做到这一点,你需要使用方法的语法。
What you need to do is to somehow await
each call to getImage()
. One way to do this is to use async
lambda in your select
. But to do that, you need to use the method syntax.
当你这样做,你将有的IEnumerable&LT;任务&LT; A&GT;&GT;
(其中 A
是匿名类型),但你只需要的IEnumerable&LT; A&GT;
。要获取,使用 Task.WhenAll()
(这将返回任务&LT; A []&GT;
),然后等待
其结果是:
When you do that, you will have IEnumerable<Task<a>>
(where a
is your anonymous type), but you need just IEnumerable<a>
. To get that, use Task.WhenAll()
(which will return Task<a[]>
) and then await
its result:
var tasks = myPictures.Select(
async file => new { Subtitle = "subtitle", Title = "title", Image = await getImage(file.Path) });
var data = await Task.WhenAll(tasks);
这将执行所有的的getImage()
■在一次,这可能不是最有效的解决方案。如果你不希望出现这种情况,就需要不同的解决方案。
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.
这篇关于如何显示从图片目录图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!