我正在使用MVVM,在我的ViewModel中,我有一些BitmapData集合。 我希望它们通过数据绑定显示在我的视图中。
我该怎么做?
解决方案:
[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 :(得分:2)
您可以从图像文件路径设置Image.Source这一事实可能会导致自动转换(由ImageSourceConverter提供)。
如果您想将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有助于实现转化。
答案 1 :(得分: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();
}
}