2011-10-25 46 views
0

我使用绑定到UI上的图像属性的viewmodel,并且viewmodel包含ImageSource属性。我使用下面的函数WPF冻结BitmapImage不显示

private BitmapImage GetImageFromUri(Uri urisource) 
    { 
     if (urisource == null) 
      return null; 

     var image = new BitmapImage(); 
     image.BeginInit(); 
     image.UriSource = urisource; 
     image.EndInit(); 
     image.Freeze(); //commenting this shows the image if the routine is called from the proper thread. 

     return image; 
    } 

对于一些奇怪的原因,在下面的代码,当我打电话冻结我的BitmapImage,它不会出现在主window.I得不到异常或死机设置该属性。任何人都可以帮助我吗? 我设置图像属性异步,所以我需要能够使用创建的图像,假设GetImageFromUri调用是从一个线程以外的UI线程。

回答

0

冻结之前,您需要完全呈现它。
您应该尝试聆听SourceUpdated事件,然后才冻结图像。

在附注中,如果您想在此之后修改图像,则必须克隆它。

+0

你是什么意思呈现它? – ak3nat0n

+0

以图形方式呈现。设置源代码不会使其可视化,WPF首先需要渲染图像。看起来你在WPF得到机会之前冻结了它。 –

2

尝试在冻结BitmapImage之前设置CacheOption。看看这是否可行 -

var image = new BitmapImage(); 
image.BeginInit(); 
image.CacheOption = BitmapCacheOption.OnLoad; 
image.UriSource = urisource; 
image.EndInit(); 
image.Freeze();