2010-06-10 66 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的方法快得多,你會發現在其他地方描述過,因爲它從未將位圖數據序列化爲流。