1

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

2 回答 2

2

您可以从图像文件路径设置Image.Source的事实取决于自动转换的存在(由ImageSourceConverter提供)。

如果要将 Image.Source 绑定到BitmapData类型的对象,则必须编写一个如下所示的绑定转换器。但是,您必须了解从 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();
    }
}

也许这个问题有助于实现转换。

于 2012-07-17T09:03:01.070 回答
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();
    }
}
于 2012-07-18T11:14:59.750 回答