Databinding a System.Drawing.Image in WPF with VB.Net


The original article that I found to help me was posted by Steve Cooper and can be found at http://www.stevecooper.org/index.php/2010/08/06/databinding-a-system-drawing-image-into-a-wpf-system-windows-image/

I converted the c# code he provided into VB code and added some XML comments. Provided below is the one way converter class in Visual Basic. Thanks to Steve for his original post.

Imports System
Imports System.Drawing.Imaging
Imports System.Globalization
Imports System.IO
Imports System.Windows.Data
    
Namespace System.Windows.Media
    
    ''' <summary>
    ''' A converter that can one way convert a GDI Image into a bitmap WPF can use.
    ''' </summary>
    ''' <remarks>
    ''' Code converted from C# source found at:<br /><br />
    ''' http://www.stevecooper.org/index.php/2010/08/06/databinding-a-system-drawing-image-into-a-wpf-system-windows-image/
    ''' XAML Declaration:<br /><br />
    ''' <code>
    '''    xmlns:med="clr-namespace:System.Windows.Media"
    ''' </code>
    ''' Stick an instance of the ImageConverter into a static resource:<br /><br />
    ''' 
    ''' <code>
    '''    &lt;ListView.Resources&gt; 
    '''       &lt;med:ImageConverter x:Key=&quot;imageConverter&quot; /&gt; 
    '''    &lt;/ListView.Resources&gt; 
    ''' </code>
    ''' 
    ''' XAML to bind directly to the Image, using the converter:<br /><br />
    ''' 
    ''' <code>
    '''    &lt;Image Source="{ Binding Path=Image, Converter={StaticResource imageConverter} }" /&gt;
    ''' </code>
    ''' 
    ''' </remarks>
    Public Class ImageConverter
        Implements IValueConverter
    
        Public Function Convert(ByVal value As Object, ByVal targetType As Type, ByVal parameter As Object, ByVal culture As Globalization.CultureInfo) As Object Implements Data.IValueConverter.Convert
            If value Is Nothing Then
                Return Nothing
            End If
    
            Dim image = DirectCast(value, System.Drawing.Image)
    
            ' Winforms Image we want to get the WPF Image from...
            Dim bitmap As New System.Windows.Media.Imaging.BitmapImage
            bitmap.BeginInit()
    
            Dim memoryStream As New MemoryStream()
    
            ' Save to a memory stream...  RawFormat will help preserve the image as it is.
            image.Save(memoryStream, image.RawFormat)
    
            ' Rewind the stream...
            memoryStream.Seek(0, System.IO.SeekOrigin.Begin)
            bitmap.StreamSource = memoryStream
            bitmap.EndInit()
    
            Return bitmap
        End Function
    
        Public Function ConvertBack(ByVal value As Object, ByVal targetType As Type, ByVal parameter As Object, ByVal culture As Globalization.CultureInfo) As Object Implements Data.IValueConverter.ConvertBack
            Return Nothing
        End Function
    
    End Class
    
End Namespace