【问题标题】:INotifyChangedProperty dynamic implementation [duplicate]INotifyChangedProperty 动态实现
【发布时间】:2015-04-22 01:16:12
【问题描述】:

在大多数情况下,他们都说要编写这样的方法:

    private void OnPropertyChanged(string prop)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(prop));
        }
    }

并称之为OnPropertyChanged("PropName");。但这似乎是非常静态的,无法自动重构。有没有办法更动态地做到这一点?我考虑使用System.Diagnostic.StackTrace 类来获取属性的名称,但它看起来很难看,效率也不高,而且我无法在例如 Windows Phone 8 应用程序中访问它(为什么!?)。

【问题讨论】:

  • 你说的“静态实现”是什么意思?
  • OnPropertyChanged("PropName"); - 你必须提供编译时已知的字符串。

标签: c# .net mvvm metaprogramming


【解决方案1】:

Caliburn.micro 有一个 PropertyChangeBase 允许您使用 lambda。您可以从它继承并调用基本方法。对于Name 的属性,您可以这样做:

NotifyOfPropertyChange(() => Name);

使用 C# 6.0,您可以实现自己的基类并使用 nameof 运算符,这将有助于重构:

OnPropertyChanged(nameof(Name));

【讨论】:

【解决方案2】:

如果您使用的是 .NET Framework 4.5,则可以使用 [CallerMemberName]

所以你的代码将是:

using System.Runtime.CompilerServices;

class BetterClass : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    // Check the attribute in the following line :
    private void FirePropertyChanged([CallerMemberName] string propertyName = null)
    {
        var handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }

    private int sampleIntField;

    public int SampleIntProperty
    {
        get { return sampleIntField; }
        set
        {
            if (value != sampleIntField)
            {
                sampleIntField = value;
                // no "magic string" in the following line :
                FirePropertyChanged();
            }
        }
    }
}

如问题INotifyPropertyChanged : is [CallerMemberName] slow compared to alternatives?中所述

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多