我认为标题已经涵盖了它。考虑:
Public Class DesignItem
Private _effects As ObservableCollection(Of Effect) = New ObservableCollection(Of Effect)
Public Property Effects() As ObservableCollection(Of Effect)
Get
Return _effects
End Get
Set(ByVal value As ObservableCollection(Of Effect))
_effects = value
If Effects.Count >= 1 Then ApplyEffects()
End Set
End Property
Public Sub New()
AddHandler Effects.CollectionChanged, AddressOf Effects_CollectionChanged
End Sub
Private Sub Effects_CollectionChanged(sender As Object, e As NotifyCollectionChangedEventArgs)
Effects.Count >= 1 Then ApplyEffects()
End Sub
Public Sub ApplyEffects()
'Stuff
End Sub
End Class
当我这样做时(简短):
Public Class MainApp
Dim di As New DesignItem
di.Effects.Add(myDropShadowEffect)
End Class
CollectionChanged 事件触发并调用方法 Effects_CollectionChanged。但是,如果我这样做(简短):
Public Class MainApp
Dim di As New DesignItem
di.Effects = New ObservableCollection(Of Effect) From {myGreyScaleEffect}
di.Effects.Add(myDropShadowEffect)
End Class
CollectionChanged 事件未触发,并且 Effects_CollectionChanged 未被调用。
我在这里误解了什么?
DesignItem 构造函数中对 AddHandler 的调用仅针对 Effects 属性的初始值运行。当您使用属性设置器重新分配集合时,您必须添加一个新的处理程序以使事件正常工作(并删除旧的处理程序)
我首先会考虑是否需要设置 setter。如果没有它,您可能会得到一个具有更好封装的更简单的类