将图像.源绑定到系统.绘图.图像不显示
本文关键字:图像 绘图 显示 系统 绑定 | 更新日期: 2023-09-27 18:36:33
我正在生成一个System.Drawing.Image
对象,我将其设置为绑定的ViewModel属性。我知道图像正在正确生成,但它没有以 WPF 形式显示。System.Drawing.Image
不是与此兼容的源类型吗?
Image image = GetMyGeneratedImage();
var vm = _myViewModelFactory.CreateExport().Value;
vm.MyImage= image;
if (vm.ShowDialog(ShellView))
..
视图型号代码:
private System.Drawing.Image _myImage;
public Image MyImage
{
get { return _myImage; }
set { _myImage= value; }
}
XAML:
<Image Source="{Binding MyImage}"/>
WPF Image
控件的源代码不支持System.Drawing.Image
。您必须将其转换为BitmapSource
并且没有可用于此转换的内置方法。
但解决方案是可用的:
[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;
}
参考: http://khason.net/blog/how-to-use-systemdrawingbitmap-hbitmap-in-wpf/