2012-07-17 1 views
1

J'utilise MVVM et dans mon ViewModel j'ai des collections BitmapData. Je souhaite qu'ils apparaissent dans ma vue en tant qu'images via la liaison de données.Comment lier des données de BitmapData à WPF Image Control?

Comment puis-je faire cela?


Solution:

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

Répondre

0

Solution, grâce à 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(); 
    } 
} 
2

Le fait que vous pouvez définir Image.Source à partir d'un chemin du fichier d'image porte sur l'existence d'une conversion automatique (fournie par ImageSourceConverter). Si vous souhaitez lier Image.Source à un objet de type BitmapData, vous devrez écrire un binding converter qui pourrait ressembler à ci-dessous. Vous devez cependant vous renseigner sur les détails de l'écriture d'un WritableBitmap à partir de BitmapData.

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

Peut-être que this question est utile pour implémenter la conversion.

Questions connexes