gpt4 book ai didi

wpf - WPF DataTemplate 中的图像对象渲染速度极慢

转载 作者:行者123 更新时间:2023-12-04 19:31:37 27 4
gpt4 key购买 nike

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

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

(我的自定义类文件的)对象只有这两个字符串属性:ThumbnailPath 和 FileName。当用户选择文件夹时,BackgroundWorker 会获取文件列表并创建 File 类的实例。使用 BW 的 ReportProgress 将这些实例分派(dispatch)到 UI 线程(以 10 个为一组)。在事件处理程序中,它们被添加到绑定(bind)到我的 ListBox 的 ObservableCollection。

问题是至少要将 20-30 个文件添加到我的收藏中;在 ListBox 更新之前,UI 卡住了将近三秒钟。甚至不要问当一个文件夹包含数百个文件时会发生什么。一切都在后台妥善准备,所以我猜问题出现在 WPF 开始初始化和呈现空图像元素时。当我从 DataTemplate 中注释掉图像时,眨眼间就会更新集合及其 View 。

有什么办法可以解决这个问题吗?我知道可以在后台线程中创建整个 View 对象(一个新的 StackPanel,添加新的子标签和新的图像,设置值),但是 DataBinding 和模板的重点应该是避免需要这样做......所以如何在不失去响应能力的情况下用数据模板中的图像填充列表框?

PS:实际的缩略图是由 FFmpeg 生成并保存到一个文件中,但是这个过程只在所有项目(带有空白图像对象)显示后才开始,所以他们在这个问题的上下文中无关紧要。

最佳答案

试试这个:

将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.

关于wpf - WPF DataTemplate 中的图像对象渲染速度极慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12990266/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com