2010-06-10 72 views
0

我试图为我的列表视图和im绑定到一个实体列表建立一个项目模板。实体我有一个System.Drawing.Image,我想要显示,但到目前为止,我不能为我的生活弄清楚如何将它绑定到<Image>块。WPF内存中图像显示

每个实例和文档,我可以在互联网上找到涉及到HDD或在网站上通过uri即文件访问图像

<DataTemplate x:Key="LogoPreviewItem"> 
     <Border BorderBrush="Black" BorderThickness="1"> 
      <DockPanel Width="150" Height="100"> 
       <Image> 
        <Image.Source> 
         <!-- 
          {Binding PreviewImage} is where the System.Drawing.Image 
          is in this context 
         --> 
        </Image.Source> 
       </Image> 
       <Label DockPanel.Dock="Bottom" Content="{Binding CustomerName}" /> 
      </DockPanel> 
     </Border> 
    </DataTemplate> 
+1

看看http://stackoverflow.com/questions/686461/how-do-i-bind-a-byte-array-to-an-image-in-wpf-with-a-value-converter – volody 2010-06-10 20:04:30

回答

4

一个System.Drawing.Image对象是一个WinForms/GDI +对象,在WPF世界中确实不合适。一个纯粹的WPF程序通常不会使用System.Drawing.Image,而是使用BitmapSource。然而有时候我们会在一段时间内停留在旧的东西上。

您可以将图像从旧的技术转换成新如下:

var oldImage = ...; // System.Drawing.Image 

var oldBitmap = 
    oldImage as System.Drawing.Bitmap ?? 
    new System.Drawing.Bitmap(oldImage); 

var bitmapSource = 
    System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
    oldBitmap.GetHbitmap(System.Drawing.Color.Transparent), 
    IntPtr.Zero, 
    new Int32Rect(0, 0, oldBitmap.Width, oldBitmap.Height), 
    null); 

现在,您可以设置:

myImage.Source = bitmapSource; 

这比MemoryStream的方法快得多,你会发现在其他地方描述过,因为它从未将位图数据序列化为流。