简体   繁体   English

将Image.Source绑定到System.Drawing.Image不显示

[英]Binding Image.Source to System.Drawing.Image not displaying

I'm generating a System.Drawing.Image object which I set to my bound ViewModel property. 我正在生成一个System.Drawing.Image对象,该对象已设置为绑定的ViewModel属性。 I know the image is being generated correctly, but it is not showing in the WPF form. 我知道该图像已正确生成,但未以WPF形式显示。 Is System.Drawing.Image not a compatible source type for this? System.Drawing.Image不是与此兼容的源类型吗?

Image image = GetMyGeneratedImage();

var vm = _myViewModelFactory.CreateExport().Value;
vm.MyImage= image;

if (vm.ShowDialog(ShellView))
..

ViewModel code: ViewModel代码:

private System.Drawing.Image _myImage;

public Image MyImage
{
   get { return _myImage; }
   set { _myImage= value; }
}

XAML: XAML:

 <Image Source="{Binding MyImage}"/>

WPF Image control's source doesn't support System.Drawing.Image . WPF Image控件的源不支持System.Drawing.Image You'll have to convert it to BitmapSource and there is no built in method available for this conversion. 您必须将其转换为BitmapSource并且没有可用于此转换的内置方法。

But the solution is available: 但是可以使用该解决方案:

   [DllImport("gdi32")]
   static extern int DeleteObject(IntPtr o);

   public static BitmapSource ToBitmapSource(System.Drawing.Bitmap source)
   {
       IntPtr ip = source.GetHbitmap();
       BitmapSource bs = null;
       try
       {
           bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ip, 
              IntPtr.Zero, Int32Rect.Empty, 
              System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
       }
       finally
       {
           DeleteObject(ip);
       }

       return bs;
   }

Reference: http://khason.net/blog/how-to-use-systemdrawingbitmap-hbitmap-in-wpf/ 参考: http : //khason.net/blog/how-to-use-systemdrawingbitmap-hbitmap-in-wpf/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM