WPF DataTemplate中的图像对象渲染非常缓慢

3

我正在创建一个带缩略图的简单文件浏览器。我使用了一个带有自定义 DataTemplate 的 ListBox 来显示 ObservableCollection 中的对象。

<DataTemplate>
   <StackPanel Margin="5">
      <Image Source="{Binding Path=ThumbnailPath}"/>
      <Label Background="White" Content="{Binding Path=FileName}"/>
   </StackPanel>
</DataTemplate>

我的自定义类File只有两个字符串属性:ThumbnailPath和FileName。当用户选择一个文件夹时,BackgroundWorker会获取文件列表并创建File类的实例。这些实例使用BW的ReportProgress分组(每组10个)调度到UI线程中。在事件处理程序中,它们被添加到绑定到我的ListBox的ObservableCollection中。
问题是当要添加至少20-30个File到集合中时,UI会在更新ListBox之前冻结近三秒钟。当一个文件夹包含数百个文件时,更不用说了。一切都准备得很好,所以我想问题出现在WPF开始初始化和渲染空Image元素时。当我从DataTemplate中注释掉Image时,更新集合及其视图只需要眨眼间的时间。
有没有什么方法可以解决这个问题?我知道可以在后台线程中创建整个View对象(新的StackPanel,添加子项new Label和new Image,设置值),但DataBinding和templating的全部意义应该是避免这样做的需求...那么如何在DataTemplate中使用Image来填充ListBox而不失去响应性呢?
PS:实际缩略图是由FFmpeg生成并保存到文件中,但此过程仅在显示所有项(具有空图像对象)之后才开始,因此它们与本问题无关。

1
图像源无法绑定到字符串,应该使用ImageSource类;http://msdn.microsoft.com/en-us/library/system.windows.controls.image.aspx - Inga
1个回答

0
尝试这个:
将ThumbnailPath更改为BitmapImage类型;
设置属性时使用。
BitmapImage bi1 = new BitmapImage();
// BitmapImage.UriSource must be in a BeginInit/EndInit block
bi1.BeginInit();
bi1.UriSource = new Uri(@"C:\filepath.jpg");
 To save significant application memory, set the DecodePixelWidth or   
// DecodePixelHeight of the BitmapImage value of the image source to the desired  
// height or width of the rendered image. If you don't do this, the application will  
// cache the image as though it were rendered as its normal size rather then just  
// the size that is displayed. 
// Note: In order to preserve aspect ratio, set DecodePixelWidth 
// or DecodePixelHeight but not both.
bi1.DecodePixelWidth = 200;
bi1.EndInit();
bi1.Freeze();

//if you do not Freeze, your app will leak memory.

Jpegs都没问题,但是在性能方面,它无法很好地处理tiff图像。 - Jay

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接