2009-05-29 70 views
1

您好我想創建一個轉換器轉換成我的圖片在數據庫中,數據類型「VARBINARY(最大)」 來填充我的DataGrid WPF中,但我有2個錯誤我告訴你的轉換器:轉換爲圖像的二進制WPF;

public class BinaryToImageConverter : IValueConverter 
{ 

public object Convert(object value, System.Type targetType, object parameter, 

System.Globalization.CultureInfo culture) 
    { 

    Binary binaryData = value;// here there is the first error .How convert BinaryData to Object?? 
     if (binaryData == null) { 
      return null; 
     } 

     byte[] buffer = binaryData.ToArray(); 
     if (buffer.Length == 0) { 
       return null; 
     } 

      BitmapImage res = new BitmapImage(); 
     res.BeginInit(); 
     res.StreamSource = new System.IO.MemoryStream(buffer); 
      res.EndInit(); 
     return res; 
     } 

    public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture) 
     { 
     BitmapImage source = value;//How convert Bitmap to Object? 
      if (source == null) { 
       return null; 
      } 
      if ((source.StreamSource != null) && source.StreamSource.Length > 0) { 
      return GetBytesFromStream(source.StreamSource); 
     } 

     return null; 
     } 

    private Binary GetBytesFromStream(System.IO.Stream stream) 
    { 
      stream.Position = 0; 
     byte[] res = new byte[stream.Length + 1]; 
     using (System.IO.BinaryReader reader = new System.IO.BinaryReader(stream)) { 
       reader.Read(res, 0, (int)stream.Length); 
     } 
      return new Binary(res); 
    } 

} 

駕駛室你給我的建議,如果它是正確的或有更好的方法來做到這一點? 感謝您的幫助。 有好日子

+0

你能指出錯誤是什麼嗎? – ChrisF 2009-05-29 15:45:57

回答

2

如果值參數確實包含了類型的對象BinaryData那麼你可以強制轉換它:

Binary binaryData = (Binary)value; 

Binary binaryData = value as Binary; 

它可能會更好做的是 - 在投射之前檢查數值參數,而不是在投射之後進行檢查,就像現在一樣。

+0

謝謝TomLog,沒錯:) – JayJay 2009-05-29 16:05:38