So in the spirit of eliminating tedious tasks, I made this sub to handle both the RaiseEvent and actual changing of the property value. I have seen a few different approaches to something like this but never one that both compares the values and actually changes the value of the property. So I'm wondering if there is a reason this method shouldn't be used for some reason or another. I'm not sure how much of an impact this would have on performance or other potential issues.
''' <summary>
''' Raises <see cref="PropertyName"/> for the property whose name matches <see cref="propertyName"/>.
''' </summary>
''' <param name="value">
''' value the property is to be changed to
''' </param>
''' <param name="[property]">
''' The name of the property whose value has changed.
''' </param>
''' <param name="Override">
''' If True, will raise event without changing the value.
''' If False, checks properties field and for difference of values before raising event
''' </param>
Protected Sub NotifyPropertyChanged(value As Object, <CallerMemberName> ByVal Optional [property] As String = Nothing, Optional Override As Boolean = False)
If Override Then
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs([property]))
Else
Dim info = Me.GetType.GetField($"_{[property]}", Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance)
If info IsNot Nothing Then
Dim myvalue = info.GetValue(Me)
If (myvalue IsNot Nothing AndAlso Not myvalue.Equals(value)) _
OrElse (myvalue Is Nothing And value IsNot Nothing) Then
info.SetValue(Me, value)
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs([property]))
End If
Else
Debug.Fail($"Expected corresponding NonPublic field _{[property]} for Property {[property]} not found")
End If
End If
End Sub
Then implementation is just
Private _CustomerCount As Integer
Public Property CustomerCount As Integer
Get
Return _CustomerCount
End Get
Set(value As Integer)
NotifyPropertyChanged(value)
End Set
End Property
Aucun commentaire:
Enregistrer un commentaire