2012-07-17 90 views
1

我使用MVVM,並在我的ViewModel我有一些BitmapData集合。 我希望它們通過數據綁定在我的視圖中顯示爲圖像。如何將數據從BitmapData綁定到WPF圖像控件?

我該怎麼做?


解決方案:

[ValueConversion(typeof(BitmapData), typeof(ImageSource))] 
public class BitmapDataConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     BitmapData data = (BitmapData)value; 
     WriteableBitmap bmp = new WriteableBitmap(
      data.Width, data.Height, 
      96, 96, 
      PixelFormats.Bgr24, 
      null); 
     int len = data.Height * data.Stride; 
     bmp.WritePixels(new System.Windows.Int32Rect(0, 0, data.Width, data.Height), data.Scan0, len, data.Stride, 0, 0); 
     return bmp; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     throw new NotSupportedException(); 
    } 
} 

回答

0

解決方案,感謝Clemens。

[ValueConversion(typeof(BitmapData), typeof(ImageSource))] 
public class BitmapDataConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     BitmapData data = (BitmapData)value; 
     WriteableBitmap bmp = new WriteableBitmap(
      data.Width, data.Height, 
      96, 96, 
      PixelFormats.Bgr24, 
      null); 
     int len = data.Height * data.Stride; 
     bmp.WritePixels(new System.Windows.Int32Rect(0, 0, data.Width, data.Height), data.Scan0, len, data.Stride, 0, 0); 
     return bmp; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     throw new NotSupportedException(); 
    } 
} 
2

可以從圖像文件上的自動轉換(由ImageSourceConverter提供)的存在路徑承載設置Image.Source的事實。

如果您想將Image.Source綁定到類型爲BitmapData的對象,則必須編寫一個如下所示的binding converter。然而,您必須瞭解從BitmapData編寫WritableBitmap的詳細信息。

[ValueConversion(typeof(System.Drawing.Imaging.BitmapData), typeof(ImageSource))] 
public class BitmapDataConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     System.Drawing.Imaging.BitmapData data = (System.Drawing.Imaging.BitmapData)value; 
     WriteableBitmap bitmap = new WriteableBitmap(data.Width, data.Height, ...); 
     bitmap.WritePixels(...); 
     return bitmap; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     throw new NotSupportedException(); 
    } 
} 

也許this question有助於實現轉換。

相關問題