【发布时间】:2016-07-20 07:20:16
【问题描述】:
我正在使用此代码将图像添加到 FlowDocument 中
doc.Blocks.Add(new BlockUIContainer(image));
但是,我收到此错误:
参数 1:无法从 'System.Drawing.Image' 转换为 'System.Windows.UIElement'
如何将图像添加到 FlowDocument 中?
【问题讨论】:
标签: c# wpf image flowdocument
我正在使用此代码将图像添加到 FlowDocument 中
doc.Blocks.Add(new BlockUIContainer(image));
但是,我收到此错误:
参数 1:无法从 'System.Drawing.Image' 转换为 'System.Windows.UIElement'
如何将图像添加到 FlowDocument 中?
【问题讨论】:
标签: c# wpf image flowdocument
您想使用System.Windows.Controls.Image 而不是System.Drawing.Image。
您可以使用这段代码将您的Drawing.Image 转换为Controls.Image
public static BitmapImage ToWpfImage(this System.Drawing.Image img)
{
MemoryStream ms=new MemoryStream(); // no using here! BitmapImage will dispose the stream after loading
img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
BitmapImage bitMapImage = new BitmapImage();
bitMapImage.BeginInit();
bitMapImage.CacheOption=BitmapCacheOption.OnLoad;
bitMapImage.StreamSource=ms;
bitMapImage.EndInit();
return bitMapImage;
}
【讨论】:
Parent 的Image 添加到另一个对象。你必须断开它。一种方法是使用复制的source 创建一个新的Image
您必须将 WPF System.Windows.Controls.Image 控件放入 BlockUIContainer 中,而不是 System.Drawing.Bitmap。首先,您必须将您的Bitmap 转换为可以用作Source 的Image 的东西,例如一个 WPF BitmapImage。然后您将创建一个新的Image 控件并将其添加到您的文档中:
System.Drawing.Bitmap bitmap = ...
var bitmapImage = new BitmapImage();
using (var memoryStream = new MemoryStream())
{
bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
bitmapImage.BeginInit();
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.StreamSource = memoryStream;
bitmapImage.EndInit();
}
var image = new Image
{
Source = bitmapImage,
Stretch = Stretch.None
};
doc.Blocks.Add(new BlockUIContainer(image));
【讨论】:
像这样向您的资源添加完整的绝对值:
var img = new BitmapImage(new Uri("pack://application:,,,/(your project name);component/Resources/PangoIcon.png", UriKind.RelativeOrAbsolute));
...它会起作用的。
【讨论】: