views:

47

answers:

1

Im trying to build an Item Template for my list-view and im bound to a list of Entities. The entity I have has a System.Drawing.Image that I'd like to display, but so far I cannot for the life of me figure out how to bind it to the <Image> block.

Every example and documentation I can find on the internet pertains to Images accessible via an uri i.e. File on HDD or On Website

    <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>
A: 

A System.Drawing.Image is a WinForms / GDI+ object and is really out of place in the WPF world. A pure WPF program will generally not use System.Drawing.Image but will use BitmapSource instead. However sometimes we are stuck with the old stuff for a while.

You can convert your image from the old technology into the new as follows:

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);

Now you can set:

myImage.Source = bitmapSource;

This is much faster than the MemoryStream approach that you will find described elsewhere, since it never serializes the bitmap data to a stream.

Ray Burns