I am trying to bind structure members to Labels in Windows Forms. However, I’m unable to do this because this structure is a member of a class, and I need to bind a couple of members to Labels.
Let’s say that this structure is a System.Drawing.Point, and I want to bind X and Y property to a Label.
Imports System.ComponentModel
Public Class Form1
Implements INotifyPropertyChanged
Private _pt As Point
Public Property Pt As Point
Get
Return _pt
End Get
Set(value As Point)
_pt = value
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("Pt"))
End Set
End Property
Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Label1.DataBindings.Add("Text", Me, "Pt")
Label2.DataBindings.Add("Text", Me.Pt, "X")
Label3.DataBindings.Add("Text", Me, "Pt.Y")
End Sub
Public Event PropertyChanged(sender As Object, e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged
End Class
If I set the bindingsource to Me and datamember to structure then Label1 will show the result of ToString() method, Label2 value of X property and Label3 will not change.
But if I assign a new Point to Pt property, then only Label1 will update its value. Label2 will not because datasource is no longer the same. Also, Label3.DataBindings.Add("Text", Me, "Pt.Y") does not work, because it’s not possible that datamember is “submember”.
I have also tried to make a new Structure that implements INotifyPropertyChanged in all its properties, but no luck.
Is there a way to make binding for Label2 or Label3 possible, even if I assign new Structure to it?
My goal is to assign new Point to Me.Pt property and observe values of Pt.X and Pt.Y on Label2 and Label3 via databinding.
You almost got it right.
Label1andLabel3will work AS IS. Changeto
And
Label2will also start working.Just make sure you assign a new value through a property, and not through your
_ptfield.