如何将数据从BitmapData绑定到WPF图像控件? [英] How to bind data from BitmapData to WPF Image Control?

查看:184
本文介绍了如何将数据从BitmapData绑定到WPF图像控件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用MVVM,在我的ViewModel中,我有一些BitmapData集合。
我希望它们通过数据绑定显示在我的视图中。

I'm using MVVM and in my ViewModel I've got some BitmapData collections. I want them to appear in my View as Images through data binding.

我该怎么做?

解决方案:

[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();
    }
}


推荐答案

解决方案,感谢Clemens。

Solution, thanks to 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();
    }
}

这篇关于如何将数据从BitmapData绑定到WPF图像控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆