DataBinding: PictureBox Image to Object.Bitmap

J.C. SolvoTerra 0 Tallied Votes 1K Views Share

Did you know that you can data bind a bitmap to a PictureBox's image property, and the source image doesn't have to be in a binary format stored in a data table?

Using a standard object setup for data binding (iNotify etc.) you can easily update your program's image propertie's from one place.

Imports System.ComponentModel

Public Class Form1

    Private tObject As TestObject

    'Your test object that has a bitmap as a property
    Public Class TestObject

        'Implement the INotifyPropertyChanged Interface
        Implements INotifyPropertyChanged

        'Create a property changed event
        Private Event PropertyChanged As PropertyChangedEventHandler _
            Implements INotifyPropertyChanged.PropertyChanged

        'Create the routine to call the property changed event
        Protected Sub OnPropertyChanged(ByVal name As String)
            RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(name))
        End Sub

        'Create a property which holds your bitmap
        Private _TestImage As Bitmap
        Public Property TestImage As Bitmap
                Return _TestImage
            End Get
            Set(value As Bitmap)
                _TestImage = value

                'call the routine which raises the propertychanged event
            End Set
        End Property

    End Class

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        'Create a new object (Which has a bitmap property). Normally this would be
        'some kind of data structure
        tObject = New TestObject

        'Data bind all of your image properties to your object's bitmap property
        PictureBox1.DataBindings.Add(New Binding("Image", tObject, "TestImage", True, DataSourceUpdateMode.OnPropertyChanged))
        PictureBox2.DataBindings.Add(New Binding("Image", tObject, "TestImage", True, DataSourceUpdateMode.OnPropertyChanged))
        PictureBox3.DataBindings.Add(New Binding("Image", tObject, "TestImage", True, DataSourceUpdateMode.OnPropertyChanged))

    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim OFD As OpenFileDialog = New OpenFileDialog

        If OFD.ShowDialog = Windows.Forms.DialogResult.OK Then
            'When ever you update your object's bitmap property, all bound image 
            'properties will automatically update.
            tObject.TestImage = New Bitmap(OFD.FileName)
        End If

    End Sub

End Class