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

解決策、クレメンスに感謝します。

[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 に答える