0

Using Caliburn.Micro, NotifyPropertyChange (out of base class PropertyChangedBase) is demonstrated thus

NotifyOfPropertyChange(() => MyPropertyName)

Where MyPropertyName is, logically, a property of some kind. I'm not quite clear on how this works, but I guess since an anonymous function returning the property is given as parameter, CM can do some reflection magic to find the actual property name. Much more handy than passing "MyPropertyName" as string, since that's typo-prone.

My question is, how do I use this in VB.Net? The literal translation would be

NotifyOfPropertyChange(Function() MyPropertyName)

But that gives me

Cannot convert lambda expression to type 'string' because it is not a delegate type.

A similar error appears in C# when MyPropertyName is not actually a property, but always seems to appear in VB.

Can this be done in VB?

Sven
  • 11
  • 3

2 Answers2

1

Not an actual answer, but I've found a work-around thanks to this answer on another question: By implementing an extension method that does accept a delegate, I've been able to use NotifyOfPropertyChange without passing a string literal:

(importing System.Linq.Expressions as well as System.Runtime.CompilerServices:)

<Extension>
Public Sub NotifyOfPropertyChange(Of T)(handler As PropertyChangedBase, propertyExpression As Expression(Of Func(Of T)))
    If handler IsNot Nothing Then
        Dim body As MemberExpression = TryCast(propertyExpression.Body, MemberExpression)
        If body Is Nothing Then Throw New ArgumentException("'propertyExpression' should be a member expression")

        Dim expression As ConstantExpression = TryCast(body.Expression, ConstantExpression)
        If expression Is Nothing Then Throw New ArgumentException("'propertyExpression' body should be a constant expression")

        Dim target = Linq.Expressions.Expression.Lambda(expression).Compile().DynamicInvoke

        handler.NotifyOfPropertyChange(body.Member.Name)
    End If
End Sub

I've then been able to use

NotifyOfPropertyChange(Function() MyPropertyName)
Community
  • 1
  • 1
Sven
  • 11
  • 3
0
Public Property FirstName() As String
        Get
            Return _firstName
        End Get
        Set(ByVal value As String)
            _firstName = value
            NotifyOfPropertyChange(NameOf(FirstName))
        End Set
    End Property
  • 6
    Code-only answers are generally frowned upon on this site. Could you please edit your answer to include some comments or explanation of your code? Explanations should answer questions like: What does it do? How does it do it? Where does it go? How does it solve OP's problem? See: [How to anwser](https://stackoverflow.com/help/how-to-answer). Thanks! – Eduardo Baitello Oct 01 '19 at 18:58