我正在我的 UWP 应用中开发内部文件管理器。我通过调用此方法在 GridView 中显示 StorageFolder 的内容:
gridView.ItemsSource = await storageFolder.GetItemsAsync();
此外,我还有一个项目模板,用于可视化链接到 GridView 的文件/文件夹项目外观。我在这个模板中有一个图像对象。我想将 StorageFolder 的缩略图图像绑定(bind)到此 Image 对象的 Source
属性。但是,GetThumbnailAsync()
是一种异步方法,而不是属性。我该怎么做?
最佳答案
Also, I have an item template for visualizing a file/folder item look linked to the the GridView. I have a Image object in this template. I want to bind StorageFolder's thumbnail image to this Image object's Source property.
我觉得你可以先获取缩略图再转成图片,这样可以作为Image
的来源吗?控制。我想你需要的是这样的:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.Resources>
<local:ThumbnailToImageConverter x:Key="cvt" />
</Grid.Resources>
<GridView x:Name="gridView">
<GridView.ItemTemplate>
<DataTemplate>
<StackPanel>
<Image Source="{Binding Thumbnail, Converter={StaticResource cvt}}" Stretch="None" />
<TextBlock Text="{Binding Name}" Margin="0,5" />
</StackPanel>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
</Grid>
绑定(bind)模型的代码隐藏和类:
private ObservableCollection<Model> Collection = new ObservableCollection<Model>();
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
var files = await KnownFolders.PicturesLibrary.GetFilesAsync();
foreach (var file in files)
{
var thumbnail = await file.GetThumbnailAsync(ThumbnailMode.PicturesView, 100);
Collection.Add(new Model { Name = file.Name, Thumbnail = thumbnail });
}
gridView.ItemsSource = Collection;
}
public class Model
{
public StorageItemThumbnail Thumbnail { get; set; }
public string Name { get; set; }
}
代码ThumbnailToImageConverter
:
public class ThumbnailToImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
BitmapImage image = null;
if (value != null)
{
StorageItemThumbnail thumbnail = (StorageItemThumbnail)value;
image = new BitmapImage();
image.SetSource(thumbnail);
}
return (image);
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
因为我使用了PicturesLibrary
在我的代码中,我们需要启用 <uap:Capability Name="picturesLibrary" />
测试此代码时在 list 文件中。
关于c# - UWP 中的异步绑定(bind)缩略图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40234054/