svick 的解决方案似乎应该可行,但正如他/她所说 - 它可能不是最有效的解决方案。对于包含未知数量文件的文件夹,更好的解决方案是使用FileInformationFactory.GetVirtualizedFilesVector()
. 最好使用转换器。
我用过的东西:
获取虚拟化文件列表并绑定到 ListView
private async void GetPicturesFromGalleryFolder()
{
var queryOptions = new QueryOptions();
queryOptions.FolderDepth = FolderDepth.Shallow;
queryOptions.IndexerOption = IndexerOption.UseIndexerWhenAvailable;
queryOptions.SortOrder.Clear();
var sortEntry = new SortEntry {PropertyName = "System.DateModified", AscendingOrder = false};
queryOptions.SortOrder.Add(sortEntry);
queryOptions.FileTypeFilter.Add(".png");
var fileQuery = KnownFolders.PicturesLibrary.CreateFileQueryWithOptions(queryOptions);
var fileInformationFactory =
new FileInformationFactory(
fileQuery,
ThumbnailMode.PicturesView,
0,
ThumbnailOptions.None,
true);
MyListView.ItemsSource = fileInformationFactory.GetVirtualizedFilesVector();
}
XAML
<ListView.ItemTemplate>
<DataTemplate>
<Image
Source="{Binding Converter={StaticResource converters:IStorageItemInformationToBitmapImageConverter}"/>
</DataTemplate>
</ListView.ItemTemplate>
IStorageItemInformationToBitmapImageConverter
public class IStorageItemInformationToBitmapImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
var fileInfo = value as FileInformation;
if (fileInfo != null)
{
var bi = new BitmapImage();
// The file is being opened asynchronously but we return the BitmapImage immediately.
SetSourceAsync(bi, fileInfo);
return bi;
}
return null;
}
private async void SetSourceAsync(BitmapImage bi, FileInformation fi)
{
try
{
using (var stream = await fi.OpenReadAsync())
{
await bi.SetSourceAsync(stream);
}
}
catch
{
// ignore failure
}
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
return null;
}
}