我们采取以下案例
Public MustInherit Class AnexaClass
Inherits ObjectBase
Private _proprietar As New ProprietarClass
Public Property proprietar As ProprietarClass
Get
Return _proprietar
End Get
Set(value As ProprietarClass)
_proprietar = value
OnPropertyChanged("proprietar")
End Set
End Property
End Class
Public Class Anexa3Class
Inherits AnexaClass
Private _Proprietari As New ObservableCollection(Of ProprietarClass)
Public Property Proprietari As ObservableCollection(Of ProprietarClass)
Get
Return _Proprietari
End Get
Set(value As ObservableCollection(Of ProprietarClass))
_Proprietari = value
OnPropertyChanged("Proprietari")
If _Proprietari.Count > 0 Then
Me.proprietar = _Proprietari(0) 'this line sets Proprietar to be the same as the first item of Proprietari and it works as it should be
End If
End Set
End Property
Public MustInherit Class AnexaViewModel(Of AnexaT As {AnexaClass, New})
Inherits ObjectBase
Private _Anexa As New AnexaT
Public Property Anexa As AnexaT
Get
Return _Anexa
End Get
Set(value As AnexaT)
_Anexa = value
OnPropertyChanged("Anexa")
End Set
End Property
Public Sub ToXML()
MsgBox(Anexa.proprietar.nume) 'at this point Anexa.proprietar is nothing
MsgBox(Anexa.Proprietari(0).nume) ' but this is fine, even though Proprietari is only declared inside the derived class Anexa3Class
''Some other code''
End Sub
End Class
Public Class Anexa3ViewModel
Inherits AnexaViewModel(Of Anexa3Class)
End Class
我的程序实例化Anexa3ViewModel
,然后设置Proprietari property
将Proprietar
设置为Proprietari(0)
(当我调试时,这似乎工作正常),然后我调用{ {1}}通过命令按下按钮。内部ToXML
ToXML
内容无效,但Anexa.proprietar
具有正确的值。
显然Anexa.Proprietari(0)
属性丢失了它的值,或者存储了两个proprietar
属性,一个用于我的基类,一个用于派生类。我认为只有通过遮蔽基本属性才能实现这一点,我不会这样做。我认为有一些继承概念让我无法理解。
有人可以对此有所了解吗?
澄清1 :我知道如果我只是将一个项目添加到集合中,Proprietar
的setter就不会起火。这不是我的问题,因为我立刻设置整个集合并且它的setter被触发,我可以看到Proprietari
获得proprietar
的正确值。问题在于它到达Proprietari(0)
时会失去价值。
答案 0 :(得分:0)
在没有看到你的应用程序的其余部分的情况下,最好的猜测是你有其他代码在Anexa3Class中为Proprietari集合添加值,而不是通过属性设置整个集合。
根据您的应用需求和设计,有一些潜在的解决方法。一种方法是处理Proprietari集合上的CollectionChanged事件:
Private WithEvents _Proprietari As New ObservableCollection(Of ProprietarClass)
Private Sub _Proprietari_CollectionChanged(sender As Object, e As System.Collections.Specialized.NotifyCollectionChangedEventArgs) Handles _Proprietari.CollectionChanged
If Me.proprietar Is Nothing AndAlso e.Action = Specialized.NotifyCollectionChangedAction.Add Then
Me.proprietar = e.NewItems(0)
End If
End Sub
另一个可能的选择是将propietar更改为可覆盖的readonly属性并始终返回第0个值,但这可能会破坏OnPropertyChanged逻辑。