Search code examples
.netvb.netoopinterfaceinotifypropertychanged

Notify object references with some property changed


I need to notify object references with property changed, check the following code:

Public Class Symbol
    Implements INotifyPropertyChanged

    Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged

    Private Sub NotifyPropertyChanged(<Runtime.CompilerServices.CallerMemberName> Optional ByVal propertyName As String = Nothing)
        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
    End Sub

    Private _Price As Decimal
    Public Property Price() As Decimal
        Get
            Return _Price
        End Get
        Set(ByVal value As Decimal)
            If Not (value = _Price) Then
                _Price = value
                NotifyPropertyChanged()
            End If

        End Set
    End Property
End Class
Public Class Position
    Public Symbol As Symbol

    Public Sub New(symbol As Symbol)
        Me.Symbol = symbol
    End Sub

    Public Sub PriceChanged()
        Debug.Print($"New Price {Symbol.Price}")
    End Sub

End Class

How do I get the PriceChanged to start when Symbol price changed?


Solution

  • The obvious solution is to declare the Symbol field WithEvents. You can then include that field in a Handles clause, just as you do with controls on a form. You can use the navigation bar at the top of the code window to generate the event handler, just as do with controls on a form:

    Public Class Position
    
        Private WithEvents _symbol As Symbol
    
        Public Property Symbol As Symbol
            Get
                Return _symbol
            End Get
            Set
                _symbol = value
            End Set
        End Property
    
        Public Sub New(symbol As Symbol)
            Me.Symbol = symbol
        End Sub
    
        Public Sub Symbol_PropertyChanged(sender As Object, e As PropertyChangedEventArgs) Handles _symbol.PropertyChanged
            Debug.Print($"New Price {Symbol.Price}")
        End Sub
    
    End Class
    

    I took the liberty of implementing the rest of the class properly too.