wpf - 空白 - 如果图像源是绝对 Uri,则 WPF 中的黑色图像控件

标签 wpf image uri absolute

我在列表框控件上使用自己的数据模板。列表框项目由一个图像控件和一些文本 block 组成。

在图像源上,我绑定(bind) Uri 的属性类型(绝对 url - 例如: http://u.aimg.sk/fotky/1730/71/17307141.jpg?v=2 )

列表框大约有 50 - 300 个项目。

如果我测试应用程序,我有时会看到空白 - 白色或黑色图像而不是用户图像。

您可以在此图像上看到的问题:

enter image description here enter image description here

我想知道是什么原因导致这个问题以及如何解决这个问题。 图片来源很好,我在浏览器中查看。

感谢您的建议。

最佳答案

我认为发生的是竞争条件。当您要求显示某些图像时,某些图像尚未完成下载。这里给出了一个很好的例子http://social.msdn.microsoft.com/Forums/en/wpf/thread/dc4d6aa9-299f-4ee8-8cd4-27a21ccfc4d0我总结一下:

private ImageSource _Src;

public ImageSource Src
{
  get { return _Src; }
  set 
  {
    _Src = value;
    if (PropertyChanged != null)
      PropertyChanged(this, new PropertyChangedEventArgs("Src"));
    ((BitmapImage)_Src).DownloadCompleted += new EventHandler(MainWindow_DownloadCompleted);
  }
}

void MainWindow_DownloadCompleted(object sender, EventArgs e)
{
  PropertyChanged(this, new PropertyChangedEventArgs("Src"));
  ((BitmapImage)_Src).DownloadCompleted -= MainWindow_DownloadCompleted;
}

使用上述代码,当首次分配值时以及图像下载 100% 后,绑定(bind)到属性的图像将被告知使用 PropertyChanged 调用进行更新。这是在上面示例中使用的 DownloadCompleted 事件处理程序中处理的。这应该使它们不再显示为黑色图像,而是完全准备好的 self 。

此外,如果您使用流作为图像源,则需要确保使用 BitmapCacheOption.OnLoad。如:

BitmapImage source = new BitmapImage();
source.BeginInit();
source.CacheOption = BitmapCacheOption.OnLoad;
source.StreamSource = yourStream;
source.EndInit();

这是因为默认情况下,使用源的图像将延迟加载它,然后您的流可能已关闭,这也可能是您获得空白/黑色图像的原因。

祝你好运。

关于wpf - 空白 - 如果图像源是绝对 Uri,则 WPF 中的黑色图像控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4896524/

相关文章:

javascript - 如何在 React Native 中将文本放在图像上?

url - URL和URI之间的区别?

c# - 无法将AllowDrop、CanDragItems、CanReorderItems 属性添加到Gridview

WPF 列表框 + 扩展器事件

wpf - 从 WPF 打印/报告的最佳方法是什么?

java - 在android中加载带有图像的联系人的有效方法

android - 具有特定格式的深度链接

c# - 在 Windows 7 WPF 客户端上发布异步抛出 System.Net.WebException

html - 使英雄形象响应

jquery - 使用 jquery 从 anchor onclick 更改图像 src?