(0 votes)

Tip: How to implement INotifyPropertyChanged interface?

1 comments   /   posted by Denislav Savkov on Aug 29, 2008

INotifyPropertyChanged interface is used to notify that a property has been changed and thus to force the bound objects to take the new value.

C#

public class Client : INotifyPropertyChanged
{
    private string name;
    public event PropertyChangedEventHandler PropertyChanged;
 
    public string Name
    {
        get
        {
            return this.Name;
        }
        set
        {
            if ( this.name == value )
                return;
 
            this.name = value;
            this.OnPropertyChanged( new PropertyChangedEventArgs( "Name" ) );
        }
    }
 
    protected virtual void OnPropertyChanged( PropertyChangedEventArgs e )
    {
        if ( this.PropertyChanged != null )
            this.PropertyChanged( this, e );
    }
}

Note that the value is changed only if the new value is different. Thus we prevent the firing of the PropertyChanged event when the actual value is not changed.

Alternative way is to provide changed event for each property.

That's it!

Filed under: Binding


Comments

Comments RSS RSS
  • RE: Tip: How to implement INotifyPropertyChanged interface?  

    posted by Tapani on Oct 08, 2008 06:11

    If you define event this way:       

    public event PropertyChangedEventHandler PropertyChanged = delegate { };

    then you can remove the if-clause from OnPropertyChanged.

Add Comment