我有一个对象,其属性也是对象并绑定到文本框。我希望能够设置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
答案 0 :(得分:0)
您可以在family
类中实现一个可以实现您所需要的方法。
Public Class Family
. . .
Public Sub ReplaceFamily(newFamily As Family)
With newFamily
Me.Father = .Father
Me.Mother = .Mother
End With
End Sub
End Class
您的电话将如下所示:
fam.ReplaceFamily(fam2)
如果family
中有很多属性,则可以在ReplaceFamily
方法中使用反射,而不是单独设置每个属性。