Caliburn.Micro在VB中的NotifyOfPropertyChange

时间:2014-12-03 08:42:50

标签: wpf vb.net caliburn.micro

使用Caliburn.Micro,NotifyPropertyChange(基类PropertyChangedBase之外)被证明

NotifyOfPropertyChange(() => MyPropertyName)

MyPropertyName在逻辑上是某种属性。我不太清楚它是如何工作的,但我想因为返回属性的匿名函数是作为参数给出的,CM可以做一些反射魔法来查找实际的属性名称。比将“MyPropertyName”作为字符串传递更方便,因为这很容易出错。

我的问题是,如何在VB.Net中使用它?字面翻译将是

NotifyOfPropertyChange(Function() MyPropertyName)

但那给了我

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

当MyPropertyName实际上不是属性时,C#中会出现类似的错误,但似乎总是出现在VB中。

可以在VB中完成吗?

2 个答案:

答案 0 :(得分:1)

不是一个真正的答案,但我找到了一个解决方法,感谢this answer on another question: 通过实现一个接受委托的扩展方法,我已经能够使用NotifyOfPropertyChange而不传递字符串文字:

(导入System.Linq.Expressions以及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

然后我就可以使用

NotifyOfPropertyChange(Function() MyPropertyName)

答案 1 :(得分: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