我知道这已经被讨论了很多,但我无法让它发挥作用。
我在 WPF 中有一个视图 - ViewModel - 模型。我需要传递模型中的属性已更改的信息。我需要最终在视图中处理信息。请注意,这里没有从 View 到 ViewModel 的数据绑定。
在ViewModel我有一组模型对象:
Public Property Items as ObservableCollection(Of Item)
模型是:
Public Class Item
Public Property Name as String
End Class
我想要做的是在 ViewModel 中的集合“Items”中的任何项目中更改属性“Name”时运行的 View 代码隐藏(见下文)中运行一个过程。
查看:
Private Sub NameWasChanged()
'do something to UI...
'Item that was changed must be known here as must the new value for the "Name" property
End Sub
更新 1 >>>
为了响应您的自定义类,我尝试将其转换为 VB.NET(如下),但看起来在此派生类中覆盖事件存在一些问题。不知道“受保护的阴影事件 PropertyChanged”是否是正确的方法。我得到 item.PropertyChanged 说“PropertyChanged 不是 T 事件”。
你能帮我解决这个问题吗?否则我得到了这个概念/想法。
Public Class BaseCollection(Of T)
Inherits ObservableCollection(Of T)
Implements INotifyPropertyChanged
Protected currentItem As T
Public Sub New(collection As IEnumerable(Of T))
Me.New()
For Each item As T In collection
Add(item)
Next
End Sub
Public Sub New(collection As ObservableCollection(Of T))
Me.New(TryCast(collection, IEnumerable(Of T)))
End Sub
Public Sub New(ParamArray collection As T())
Me.New(TryCast(collection, IEnumerable(Of T)))
End Sub
Public Sub New()
MyBase.New()
End Sub
Public Shadows Sub Add(item As T)
AddHandler item.PropertyChanged, AddressOf Item_PropertyChanged
MyBase.Add(item)
End Sub
Public Overridable Shadows Sub Add(collection As IEnumerable(Of T))
For Each item As T In collection
Add(item)
Next
End Sub
Public Overridable Shadows Sub Add(ParamArray items As T())
Add(TryCast(items, IEnumerable(Of T)))
End Sub
Protected Overrides Sub InsertItem(index As Integer, item As T)
If item IsNot Nothing Then
AddHandler item.PropertyChanged, AddressOf Item_PropertyChanged
MyBase.InsertItem(index, item)
End If
End Sub
Protected Overrides Sub ClearItems()
For Each item As T In Me
RemoveHandler item.PropertyChanged, AddressOf Item_PropertyChanged
Next
MyBase.ClearItems()
End Sub
Public Shadows Function Remove(item As T) As Boolean
If item Is Nothing Then
Return False
End If
RemoveHandler item.PropertyChanged, AddressOf Item_PropertyChanged
Return MyBase.Remove(item)
End Function
Public Shadows Sub RemoveAt(index As Integer)
Dim item As T = Me(index)
If item IsNot Nothing Then
RemoveHandler item.PropertyChanged, AddressOf Item_PropertyChanged
End If
MyBase.RemoveAt(index)
End Sub
Private Sub Item_PropertyChanged(sender As Object, e As PropertyChangedEventArgs)
NotifyPropertyChanged(e.PropertyName)
End Sub
#Region "INotifyPropertyChanged Members"
Protected Shadows Event PropertyChanged As PropertyChangedEventHandler
Protected Overridable Sub NotifyPropertyChanged(ParamArray propertyNames As String())
For Each propertyName As String In propertyNames
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
Next
End Sub
#End Region
End Class