2012-07-17 95 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有助于实现转换。

相关问题