Hi Roger, try following demo:
XAML:
<Window x:Class="Window001"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="Demo load picture from database" Height="450" Width="800">
<Window.DataContext>
<local:Window001VM/>
</Window.DataContext>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Image Source="{Binding Picture}"/>
<StackPanel Grid.Column="1">
<Button Content="Prepare Database" Command="{Binding Cmd}" CommandParameter="Create" Margin="5"/>
<Button Content="Load Picture" Command="{Binding Cmd}" CommandParameter="Load" Margin="5"/>
</StackPanel>
</Grid>
</Window>
ViewModel:
Imports System.ComponentModel
Imports System.Data
Imports System.Data.SqlClient
Imports System.IO
Imports System.Runtime.CompilerServices
Public Class Window001VM
Implements INotifyPropertyChanged
Public Property Picture As BitmapImage
Public ReadOnly Property Cmd As ICommand = New RelayCommand(AddressOf CmdExec)
Private Sub CmdExec(obj As Object)
Select Case obj.ToString
Case "Create"
Using cn As New SqlConnection(My.Settings.cnSQL)
cn.Open()
Using cmd As New SqlCommand With {.Connection = cn}
' delete previous table in SQL Server 2016 and above
'cmd.CommandText = "DROP TABLE IF EXISTS Table1;"
' delete previous table in previous versions of SQL server 2016
cmd.CommandText = "If OBJECT_ID('Table1', 'U') IS NOT NULL DROP TABLE IF EXISTS Table1;"
Debug.Print($"Return value Drop: {cmd.ExecuteNonQuery}")
' Cretae Table
cmd.CommandText = "CREATE Table Table1([ID] Integer Identity, [Picture] image, CONSTRAINT [PK_Table1] PRIMARY KEY ([ID]));"
Debug.Print($"Return value Create Table: {cmd.ExecuteNonQuery}")
' Insert Record with Picture from file system
cmd.CommandText = "INSERT Table1([Picture]) VALUES(@pict);"
cmd.Parameters.Add("@pict", SqlDbType.Image).Value = File.ReadAllBytes("Image.jpg")
Debug.Print($"Return value Insert Picture: {cmd.ExecuteNonQuery}")
End Using
End Using
Case "Load"
Using cn As New SqlConnection(My.Settings.cnSQL)
cn.Open()
Using cmd As New SqlCommand With {.Connection = cn}
cmd.CommandText = "SELECT * FROM Table1;"
Dim rdr = cmd.ExecuteReader
rdr.Read()
Dim buf = CType(rdr(1), Byte())
Dim ms As New MemoryStream(buf)
Dim img As New BitmapImage()
img.BeginInit()
img.StreamSource = ms
img.EndInit()
Picture = img
OnPropertyChanged(NameOf(Picture))
End Using
End Using
End Select
End Sub
Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
Private Sub OnPropertyChanged(<CallerMemberName> Optional propName As String = "")
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propName))
End Sub
End Class