【问题标题】:Caliburn.Micro's NotifyOfPropertyChange in VBVB 中的 Caliburn.Micro NotifyOfPropertyChange
【发布时间】:2015-01-31 17:50:28
【问题描述】:

使用 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 中完成吗?

【问题讨论】:

    标签: wpf vb.net caliburn.micro


    【解决方案1】:
    Public Property FirstName() As String
            Get
                Return _firstName
            End Get
            Set(ByVal value As String)
                _firstName = value
                NotifyOfPropertyChange(NameOf(FirstName))
            End Set
        End Property
    

    【讨论】:

    • 本网站上通常不赞成仅使用代码的答案。您能否编辑您的答案以包含一些 cmets 或对您的代码的解释?解释应该回答这样的问题:它有什么作用?它是如何做到的?它去哪儿了?它如何解决OP的问题?请参阅:How to anwser。谢谢!
    【解决方案2】:

    不是一个实际的答案,但感谢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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-27
      • 1970-01-01
      • 2014-09-14
      • 2022-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多