simonalexander2005 simonalexander2005 - 1 month ago 4 Question

Is it possible to override the Parameter keyword, or create a new Keyword, for observable properties?

In VB.NET (without referencing 3rd-party libraries), I am finding that I am writing a lot of the following code:

Private _prop as String = "test"
Public Property Prop As String
Return _prop
End Get
Set(value As String)
_prop = value
End Set

'(add more properties here...)

Public Event PropertyChanged(sender As Object, e As PropertyChangedEventArgs) Implements INotifyPropertyChanged.PropertyChanged
Protected Overridable Sub NotifyPropertyChanged(<CallerMemberName> Optional propertyName As String = "")
If PropertyChangedEvent IsNot Nothing Then
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
End If
End Sub

What I would like to be able to do is something like:

Public ObservableProperty Prop As String = "test"

and have ObservableProperty be a construct I define that does all the boilerplate stuff.

I know that if I didn't want it to be Observable, I could use that same pattern (
Public Property NonObsProp As String = "test"
), so is it possible to make them observable automatically also?


A comment from @sstan pointed me in the right direction. It's not a perfect answer, but it's the closest I'm going to get for now.

Essentially, it's the way referred to here, which suggests creating a SetProperty method which calls NotifyPropertyChanged, cutting down on the boilerplate code.

Something like:

protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
        if (Equals(storage, value))
            return false;

        storage = value;
        return true;