我有一个对象,它的属性也是对象并绑定到文本框。我希望能够设置 MyOriginalObj = MyNewOject 并让文本框显示新值。这不起作用。我要做的是 MyOriginalObj.PropertyA = MyNewObj.PropertyA。这将导致文本框更新。
我想避免使用后一种方法,因为我的实际类比下面的测试类具有更多的属性,并且会增加执行所有更新所需的代码。如果必须的话,我想我可以取消绑定并绑定到新对象,但这又是添加更多代码。MyOriginalObj = MyNewObj 方法将是最简单的解决方案,但我不确定是否可行。请指教。
Dim fam As New Family
Public Class Person
Dim _Age As Integer = 0
Dim _Name As String = ""
Public Property Age() As Integer
Get
Return _Age
End Get
Set(ByVal value As Integer)
_Age = value
End Set
End Property
Public Property Name() As String
Get
Return _Name
End Get
Set(ByVal value As String)
_Name = value
End Set
End Property
Public Sub New(ByVal age As Integer, ByVal name As String)
With Me
._Age = age
._Name = name
End With
End Sub
End Class
-
Public Class Family
Implements System.ComponentModel.INotifyPropertyChanged
Public Event PropertyChanged(ByVal sender As Object,
ByVal e As System.ComponentModel.PropertyChangedEventArgs) _
Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged
Dim _Father As New Person(0, "")
Dim _Mother As New Person(0, "")
Public Property Father() As Person
Get
Return _Father
End Get
Set(ByVal value As Person)
_Father = value
RaiseEvent PropertyChanged(Me,
New System.ComponentModel.PropertyChangedEventArgs("Father"))
End Set
End Property
Public Property Mother() As Person
Get
Return _Mother
End Get
Set(ByVal value As Person)
_Mother = value
RaiseEvent PropertyChanged(Me,
New System.ComponentModel.PropertyChangedEventArgs("Mother"))
End Set
End Property
End Class
-
Private Sub Form1_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
TextBox1.DataBindings.Add("Text", fam, "Father.Name")
TextBox2.DataBindings.Add("Text", fam, "Mother.Name")
End Sub
-
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
' Method A - works, textboxes displays the new values.
' fam.Father = New Person(30, "Joe")
' fam.Mother = New Person(29, "Jane")
' Exit Sub
' Method B - does not update textboxes.
Dim fam2 As New Family
fam2.Father = New Person(40, "Bob")
fam2.Mother = New Person(39, "Betty")
' I would like the updated properties to be shown in the bound
' textboxes when I set fam = fam2. Object fam will contain
' the new values but the textboxes will not reflect that.
fam = fam2
Console.WriteLine("{0},{1} : {2}, {3}", _
fam.Father.Name, _
fam.Father.Age, _
fam.Mother.Name, _
fam.Mother.Age)
End Sub