Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
How to: Implement the INotifyPropertyChanged Interface

How to: Implement the INotifyPropertyChanged Interface 

The following code example demonstrates how to implement the INotifyPropertyChanged interface. Implement this interface on business objects that are used in Windows Forms data binding. When implemented, the interface communicates to a bound control the property changes on a business object.

Example

// This class implements a simple customer type 
// that implements the IPropertyChange interface.
public class DemoCustomer : INotifyPropertyChanged
{
    // These fields hold the values for the public properties.
    private Guid idValue = Guid.NewGuid();
    private string customerName = String.Empty;
    private string companyNameValue = String.Empty;
    private string phoneNumberValue = String.Empty;

    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(String info)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(info));
        }
    }

    // The constructor is private to enforce the factory pattern.
    private DemoCustomer()
    {
        customerName = "no data";
        companyNameValue = "no data";
        phoneNumberValue = "no data";
    }

    // This is the public factory method.
    public static DemoCustomer CreateNewCustomer()
    {
        return new DemoCustomer();
    }

    // This property represents an ID, suitable
    // for use as a primary key in a database.
    public Guid ID
    {
        get
        {
            return this.idValue;
        }
    }

    public string CompanyName
    {
        get {return this.companyNameValue;}
       
        set
        {
            if (value != this.companyNameValue)
            {
                this.companyNameValue = value;
                NotifyPropertyChanged("CompanyName");
            }
        }
    }
    public string PhoneNumber
    {
        get { return this.phoneNumberValue; }
        
        set 
        {
            if (value != this.companyNameValue)
            {
                this.phoneNumberValue = value;
                NotifyPropertyChanged("PhoneNumber");
            }
        }
    }
}

Compiling the Code

To compile the previous code example:

  • Paste the code into an empty code file. Use the business object in a Windows Forms application that contains a Main method.

See Also

Community Additions

ADD
Show:
© 2015 Microsoft