WPF BitmapSource ImageSource

use*_*309 7 c# wpf xaml binding

我将Image.Source属性绑定到下面显示的属性的结果.

public BitmapSource MyImageSource
{
    get
    {
        BitmapSource source = null;

        PngBitmapDecoder decoder;
        using (var stream = new FileStream(@"C:\Temp\logo.png", FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            decoder = new PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None);

            if (decoder.Frames != null && decoder.Frames.Count > 0)
                source = decoder.Frames[0];
        }

        return source;
    }
}
Run Code Online (Sandbox Code Playgroud)

由于某些原因,在渲染图像期间(在PresentationCore程序集中为Deep)失败.我确信图像没有损坏,因为我可以成功显示没有绑定的相同图像

<Image Name="FooImage" Source="/logo.png" />
Run Code Online (Sandbox Code Playgroud)

我必须在代码中绑定图像源,因为我最终将从base64字符串创建图像流.

任何人都知道这是否是WPF的错误?还是我做错了什么?

use*_*309 11

问题是BitmapCacheOption选项,更改为BitmapCacheOption.OnLoad工作.

使用BitmapCacheOption.None时,BitmapSource在渲染图像之前不会被解码,但是其中包含png的流已经被放置在那个点上.如果你缓存OnLoad,它会立即解码并缓存结果,而不是在流不再存在时尝试解码.