Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variable/property changed event in vb.net

How can I make an event that is raised when a variable or property is changed (or can I just put the code I would put in an event in the Set section of a property?

like image 368
Jonathan. Avatar asked Dec 01 '22 06:12

Jonathan.


2 Answers

From the MSDN library entry INotifyPropertyChanged.PropertyChanged Event:

Public Class DemoCustomer
    Implements INotifyPropertyChanged

    Private customerNameValue As String = String.Empty

    Public Event PropertyChanged As PropertyChangedEventHandler _
        Implements INotifyPropertyChanged.PropertyChanged

    Private Sub NotifyPropertyChanged(ByVal info As String)
        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(info))
    End Sub

    Public Property CustomerName() As String
        Get
            Return Me.customerNameValue
        End Get

        Set(ByVal value As String)
            If Not (value = customerNameValue) Then
                Me.customerNameValue = value
                NotifyPropertyChanged("CustomerName")
            End If
        End Set
    End Property
End Class
like image 175
Aviad P. Avatar answered Dec 04 '22 13:12

Aviad P.


Yes, the best (if not the only) way of doing this is to completely hide the actual variable (make it Private) and expose it via a Property which fires events whenever the setter is used.

I do this regularly, but I've found that it's important to NOT raise the event if the new value is similar to the old value. This both eliminates unnecessary function calls and sometimes prevents recursive events.

like image 24
David Rutten Avatar answered Dec 04 '22 14:12

David Rutten