我编写了一个应用程序,它从操作系统获取文件图标并绑定到它们,但由于System.Drawing.Icon对象不能用作Image控件中的ImageSource,我不得不编写一个转换器。
经过一番搜索后,我得到了以下代码,我目前正在使用它:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Icon ico = (value as Icon);
Bitmap bits = ico.ToBitmap();
MemoryStream strm = new MemoryStream();
// add the stream to the image streams collection so we can get rid of it later
_imageStreams.Add(strm);
bits.Save(strm, System.Drawing.Imaging.ImageFormat.Png);
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.StreamSource = strm;
bitmap.EndInit();
// freeze it here for performance
bitmap.Freeze();
return bitmap;
}
我有三个问题:
您可以提出更好的解决方案吗?
最终关闭使用的
MemoryStream
s 的最佳方法是什么,因为这里的代码是由绑定系统自动调用的?(它们从不手动实例化,您可能会注意到我将流添加到集合中Close()
,在析构函数中调用它们,但我认为这不是一个好的解决方案)。与上一个问题相关,当我尝试在函数结束之前关闭流时,即使在此之前调用Stream.Flush() ,图像也会显示为空。为什么是这样?