使用XAML将System.Drawing.Image绑定到System.Windows.Image控件
我正在将ListView绑定到对象列表,就像这样;
我绑定到一个声明两个属性的对象;
string DisplayName { get; } System.Drawing.Image Image { get; set; }
我想填充DataTemplate
但我无法弄清楚如何; 如果我在我的模板中这样做;
文本出现但图像没有。 我究竟做错了什么? 调试输出显示
System.Windows.Data Error: 1 : Cannot create default converter to perform 'one-way' conversions between types 'System.Drawing.Image' and 'System.Windows.Media.ImageSource'. Consider using Converter property of Binding. BindingExpression:Path=Image; DataItem='RealElement' (HashCode=54308798); target element is 'Image' (Name=''); target property is 'Source' (type 'ImageSource')
找到了一种我很满意的方式。 使用Reed Copsey的指针和本教程,我将代码包装为IValueConverter
。
这是从System.Drawing.Image
到System.Windows.Media.ImageSource
的转换器;
using System; using System.Drawing.Imaging; using System.Globalization; using System.IO; using System.Windows.Data; namespace System.Windows.Media { /// /// One-way converter from System.Drawing.Image to System.Windows.Media.ImageSource /// [ValueConversion(typeof(System.Drawing.Image), typeof(System.Windows.Media.ImageSource))] public class ImageConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { // empty images are empty... if (value == null) { return null; } var image = (System.Drawing.Image)value; // Winforms Image we want to get the WPF Image from... var bitmap = new System.Windows.Media.Imaging.BitmapImage(); bitmap.BeginInit(); MemoryStream memoryStream = new MemoryStream(); // Save to a memory stream... image.Save(memoryStream, ImageFormat.Bmp); // Rewind the stream... memoryStream.Seek(0, System.IO.SeekOrigin.Begin); bitmap.StreamSource = memoryStream; bitmap.EndInit(); return bitmap; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } }
然后,您需要将图像转换器作为资源引入XAML;
xmlns:med="clr-namespace:System.Windows.Media" ...
然后你可以在XAML中使用它直接绑定到Image,使用新的转换器;
你无法直接绑定它 – 你需要有一些类型的转换器,它将从GDI图像转换为WPF图像。
这是一种方法 – 它使用内存流从GDI图像中提取数据并创建BitmapSource对象。