Search code examples
vb.netsql-server-2008windows-phone-7wcf-data-servicesvb.net-2010

Cannot Convert Byte to Image Windows Phone


Assalamu'alaikum. Hi, guys i have a problem when i convert image byte data type to image on PictureBox in Windows Phone. It says "InvalidCastExpection was unhandled".

This is code behind :

Namespace WP7_ClientApp
    Public Class ImageConverter
        Implements IValueConverter
        Public Function ubah(ByVal value As Object, ByVal targetType As Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements IValueConverter.Convert
            Dim memStream As New MemoryStream(CType(value, Byte()))
            memStream.Seek(0, SeekOrigin.Begin)
            Dim gambar As New BitmapImage()
            gambar.SetSource(memStream)
            Return gambar
        End Function

        Public Function ConvertBack(ByVal value As Object, ByVal targetType As Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements IValueConverter.ConvertBack
            Throw New NotImplementedException()
        End Function
    End Class
End Namespace

Then this is XAML code :

 <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <ListBox x:Name="daftar" ItemsSource="{Binding}"  HorizontalAlignment="Left" Height="599" VerticalAlignment="Top" Width="456" Margin="12,10,0,0" Grid.Row="1">
                <ListBox.ItemTemplate>
                   <DataTemplate>
                    <StackPanel Orientation="Horizontal" >
                        <Image Height="100" Source="{Binding gambar,Converter={StaticResource ImageConverter}}" HorizontalAlignment="Left" Margin="10,10,0,0" Name="Image1" Stretch="Fill" VerticalAlignment="Top" Width="100" />
                        <TextBlock Margin="10" Text="{Binding id}"/>
                        <TextBlock Margin="10" Text="{Binding namaproduk}"/>
                        <TextBlock Margin="10" Text="{Binding hargaproduk}"/>
                        <TextBlock Margin="10" Text="{Binding keterangan}"/>
                    </StackPanel>
                   </DataTemplate>
                    </ListBox.ItemTemplate>
            </ListBox> 
        </Grid>

And then this is error screenshot : http://4.bp.blogspot.com/-qWB7oKLVE-s/UfpE0jhnhsI/AAAAAAAABuo/2eNvw2AmTEk/s1600/Capture.PNG

Anyone can solve this? I would be very happy, thank you.

*Note : The gambar data type is Image which is has a byte data type, my table : http://4.bp.blogspot.com/-2ZMzi32TXsg/UfpJ5RqRG6I/AAAAAAAABu4/qe81rZm1pq0/s320/Capture.PNG


Solution

  • Your object is of type Binary while your converter is expecting a byte array. Instead of binding your control to gambar, bind to gambar.Bytes.