如何在使用NotifyPropertyWeaver时获取OnPropertyChanging事件?

时间:2012-08-06 11:27:41

标签: c# inotifypropertychanged automatic-properties

我使用NotifyPropertyWeaverMsBuildTask来处理NotifyPropertyChanged以获取自动属性。我知道当属性值改变时,OnPropertyChanged()方法会上升。但是当调用此方法时,属性值会发生变化而旧值会丢失。有没有办法获得旧价值?

坦。

2 个答案:

答案 0 :(得分:3)

INotifyPropertyChanged没有提供捕获属性的先前值的方法;你必须实现自己的。

答案 1 :(得分:3)

如果你想在OnPropertyChanged中使用旧值,那么就像这样写

public void OnPropertyChanged(string propertyName, object before, object after)

然后,如果您的代码看起来像这样

public class Person : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public string Name { get; set; }

    public void OnPropertyChanged(string propertyName, object before, object after)
    {
        // do something with before/after
        var propertyChanged = PropertyChanged;
        if (propertyChanged != null)
        {
            propertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

这将被注入

public class Person : INotifyPropertyChanged
{
    private string name;

    public event PropertyChangedEventHandler PropertyChanged;

    public string Name
    {
        get { return name; }
        set
        {
            object before = Name;
            name = value;
            OnPropertyChanged("Name", before, Name);
        }
    }

    public void OnPropertyChanged(string propertyName, object before, object after)
    {            
        // do something with before/after
        var propertyChanged = PropertyChanged;
        if (propertyChanged != null)
        {
            propertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

此处提供了更多信息https://github.com/SimonCropp/NotifyPropertyWeaver/wiki/BeforeAfter

这是否符合您的要求?