2

在 aValueConverter中,我试图将System.Data.Linq.Binary(SQL CE 映像)转换为BitmapImage. 此方法有效(图像在表单上正确显示):

public object Convert(object value, Type targetType, object parameter, 
                                                     CultureInfo culture) {
    Binary binary = value as Binary;
    if (binary != null) {
        BitmapImage bitmap = new BitmapImage();
        bitmap.BeginInit();
        bitmap.StreamSource = new MemoryStream(binary.ToArray());
        bitmap.EndInit();
        return bitmap;
    }
    return null;
}

此方法不起作用但奇怪的是没有抛出异常):

public object Convert(object value, Type targetType, object parameter, 
                                                     CultureInfo culture) {
    Binary binary = value as Binary;
    if (binary != null) {
        using (var stream = new MemoryStream(binary.ToArray())) {
            BitmapImage bitmap = new BitmapImage();
            bitmap.BeginInit();
            bitmap.StreamSource = stream;
            bitmap.EndInit();
            return bitmap;
        }
    }
    return null;
}

良好的编程实践表明您应该处理您创建的任何流......所以我很困惑为什么第二种方法不起作用,但第一种方法起作用。有什么见解吗?

4

2 回答 2

2

试试这个:

public object Convert(object value, Type targetType, object parameter, 
                                                     CultureInfo culture) {
    Binary binary = value as Binary;
    if (binary != null) {
        using (var stream = new MemoryStream(binary.ToArray())) {
            BitmapImage bitmap = new BitmapImage();
            bitmap.BeginInit();
            bitmap.CacheOption = BitmapCacheOption.OnLoad; 
            bitmap.StreamSource = stream;
            bitmap.EndInit();
            bitmap.Freeze(); 
            return bitmap;
        }
    }
    return null;
}

在您的非工作版本中,您的using块意味着在实际解码图像之前关闭流。

于 2011-01-23T03:46:50.310 回答
0

我的猜测是,当您处理 时MemoryStream,您正在取消StreamSource位图的 。因此,当位图尝试渲染时,没有可用的有效数据。

于 2011-01-23T03:47:19.430 回答