Pages

Wednesday, January 25, 2012

C# Class Implementation of INotifyPropertyChanged

A simple C# class implementing INotifyPropertyChanged:
INotifyPropertyChanged implements one event:
//Event raised anytime a property on the object changes.
public event PropertyChangedEventHandler PropertyChanged;

which is raised anytime a property on the object is changed.




With the class, include a helper function to handle any change with any object property. It can be name any generic name. When raised, it is passed the proptery name as a string.


//Write a helper function
public void OnPropertyChanged(string propertyName)
{
    //Anyone listening?
    if (PropertyChanged != null)
    {
        //Raise the event
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}


Raise the event in any property within the object.


public double password
{
    get { return _password; }
 
    set
    {
        if (value != _password)
        {
            _password = value;
 
            //Will raise the PropertyChanged event.
            OnPropertyChanged("password");
        }
    }
}

Now, when anytime an object’s property changes, the PropertyChanged will be fired.

Complete code below:


public class Person : INotifyPropertyChanged
{
    private double _password;
    public string username { get; set; }
    public double password
    {
        get { return _password; }
 
        set
        {
            if (value != _password)
            {
                _password = value;
                //Will raise the PropertyChanged event.
                OnPropertyChanged("password");
            }
        }
    }
 
    //Event raised anytime a property on the object changes.
    public event PropertyChangedEventHandler PropertyChanged;
 
    //Write a helper function
    public void OnPropertyChanged(string propertyName)
    {
        //Anyone listening?
        if (PropertyChanged != null)
        {
            //Raise the event
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

1 comment:

  1. Very nice, I really disliked the idea of using strings to notify property changes!
    Do Expression Trees use Reflection to perform these tricks? Just wondering as I generally try to avoid using Reflection at all costs.
    http://www.dapfor.com/en/net-suite/net-grid/features/performance

    ReplyDelete