Skip to content

BeforeAfter

Simon Cropp edited this page Jul 30, 2012 · 2 revisions

Sometimes it is useful to have access to the value of the property be changed from OnPropertyChanged. For example to avoid reflection when implementing IDataErrorInfo or INotifyDataErrorInfo. This can be achieved by having the following signature for OnPropertyChanged.

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

So for example if your code looks like this

public class Person : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public string Name { get; set; }

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

The following will be compiled

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)
    {
        //Perform property validation
        var propertyChanged = PropertyChanged;
        if (propertyChanged != null)
        {
            propertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
Clone this wiki locally