开发者

Blank - Black Image control in WPF if image source is absolute Uri

开发者 https://www.devze.com 2023-02-09 01:49 出处:网络
I use on listbox control own datatemplate. Listbox item consist one image control and some textblock.

I use on listbox control own datatemplate. Listbox item consist one image control and some textblock.

On image source I bind property type of Uri (absolute url - for example: http://u.aimg.sk/fotky/1730/71/17307141.jpg?v=2)

Listbox have about 50 - 300 items.

If I test 开发者_C百科app, I sometimes see blank - white or black image instead user images.

The problem you can see on this images:

Blank - Black Image control in WPF if image source is absolute Uri

Blank - Black Image control in WPF if image source is absolute Uri

I would like to know what cause this problem and how can I solve this problem. Image sources are good, I check it in browser.

Thank for advice.


I think what's happening is a race condition. Some of your images haven't completed downloading by the time you are asking them to display. There is a pretty good example given here http://social.msdn.microsoft.com/Forums/en/wpf/thread/dc4d6aa9-299f-4ee8-8cd4-27a21ccfc4d0 which I'll sum up:

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;
}

With the above code, your images that are binding to your property will be told to update with the PropertyChanged call when the value is first assigned as well as AFTER the images have downloaded 100%. This is taken care of in the DownloadCompleted event handler that is utilized in the above example. This should make them not appear as a black image anymore, but as their fully-ready selves.

Also, if you are using a stream to as the source for your images, you need to make sure you use BitmapCacheOption.OnLoad. Such as:

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

This is because by default the image using the source will lazy load it and by then your stream is probably closed, which could also be why you get blank/black images.

Good luck.

0

精彩评论

暂无评论...
验证码 换一张
取 消