How to: Apply the PropertyNameChanged Pattern

How to: Apply the PropertyNameChanged Pattern


The following code example demonstrates how to apply the PropertyNameChanged pattern to a custom control. Apply this pattern when you implement custom controls that are used with the Windows Forms data binding engine.


' This class implements a simple user control 
' that demonstrates how to apply the propertyNameChanged pattern.
<ComplexBindingProperties("DataSource", "DataMember")>  _
Public Class CustomerControl
    Inherits UserControl
    Private dataGridView1 As DataGridView
    Private label1 As Label
    Private lastUpdate As DateTime = DateTime.Now

    Public DataSourceChanged As EventHandler

    Public Property DataSource() As Object 
            Return Me.dataGridView1.DataSource
        End Get
            If DataSource IsNot Value Then
                Me.dataGridView1.DataSource = Value
            End If
        End Set
    End Property

    Public Property DataMember() As String 
            Return Me.dataGridView1.DataMember
        End Get 
            Me.dataGridView1.DataMember = value
        End Set 
    End Property

    Private Sub OnDataSourceChanged() 
        If (DataSourceChanged IsNot Nothing) Then
            DataSourceChanged(Me, New EventArgs())
        End If

    End Sub

    Public Sub New() 
        Me.dataGridView1 = New System.Windows.Forms.DataGridView()
        Me.label1 = New System.Windows.Forms.Label()
        Me.dataGridView1.ColumnHeadersHeightSizeMode = _
        Me.dataGridView1.ImeMode = System.Windows.Forms.ImeMode.Disable
        Me.dataGridView1.Location = New System.Drawing.Point(19, 55)
        Me.dataGridView1.Size = New System.Drawing.Size(350, 150)
        Me.dataGridView1.TabIndex = 1
        Me.label1.AutoSize = True
        Me.label1.Location = New System.Drawing.Point(19, 23)
        Me.label1.Name = "label1"
        Me.label1.Size = New System.Drawing.Size(76, 13)
        Me.label1.TabIndex = 2
        Me.label1.Text = "Customer List:"
        Me.Size = New System.Drawing.Size(350, 216)
    End Sub
End Class

Compiling the Code

To compile the previous code example:

  • Paste the code into an empty code file. You must use the custom control on a Windows Form that contains a Main method.

© 2016 Microsoft