我使用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();
}
}