C# property changed event and INotifyPropertyChanged

+2 votes
asked Jun 28, 2013 in C#.NET by anonymous

What is the purpose of using INotifyPropertyChanged interface? I do not understand the concept behind the PropertyChanged event. Why should I use it and how to use it in C# application?

Share

1 Answer

+2 votes
answered Jun 28, 2013 by Aadhira (1,213 points)
edited Jul 11, 2013 by Aadhira
 
Best answer

INotifyPropertyChanged is an interface comes with “System.ComponentModel” that has only one event declaration called PropertyChanged. Once you derive INotifyPropertyChanged interface in your class, then your class must implement PropertyChanged event.

Why PropertyChanged Event?

Below example may not be the real situation for you, but to explain the purpose of PropertyChanged event, I have taken this scenario.

Consider a small example where, you have a class (CustomerInfo) that has some properties like (FirstName, LastName). You have a winform which is having two textboxes txtFirstName and txtLastName. These two text boxes will display FirstName and LastName respectively.

If you have created CustomerInfo object as shared and if the same CustomerInfo object is used by winform also by some other functions in your application.
When you open the form first time, you may pull the value for firstname and lastname from datasource and set those values in to the textboxes.

txtFirstName.text = _customerInfo.FirstName
txtLastName.text = _customerInfo.LastName

But, if the FirstName and LastName are changed in CustomerInfo by someother function, how does your winform will know about that unless we call a method to know whether the value of those properties got changed? Or if winform does the change then, how the other function will know about the change in value? Both the winform and other function are sharing same instance.

Instead of winform or the other function to check the CustomerInfo object, to find the value changed on FirstName or LastName property, CustomerInfo object will have an event. So that winforms and the other functions whoever is interest on the value change of properties in CustomerInfo, they can subscribe to that event. Subscribe is nothing but, telling the CustomerInfo object to inform me whenever the value changed either in FirstName or LastName.

So, if the value changed in the FirstName or LastName, CustomerInfo will raise propertychanged event. Since the propertychanged event will be raised by both FirstName and LastName property, whoever is listening to that event has to know, whether this event raised by the FirstName or LastName property value changed. To tell that information, whenever the event raised from CustomerInfo object, it will also send the name of the property for which the value is changed. Then the listeners will do action based on the property name. Now, if the value has changed by either winform or the other function, both gets the notification and they will do the respective action.

You may want to publish the propertychanged event from your custom class, then if any other class is interested in that event, they can subscribe for that event and get the notification

Why INotifyPropertyChanged?
Now, you understand why we use property changed event. Let see, why we should use INotifyPeopertyChanged interface. Instead of using this INotifyPropertyChanged interface, you can implement PropertyChanged Event directly in your class. But when you implement the INotifyPropertyChanged we are making sure that, we are implementing PropertyChanged event. If not, we/developer might forget to implement.

Another reason is, Microsoft framework is doing some work behind the scene based on this INotifyPropertyChanged interface for two way Data binding between the classes (like CustomerInfo) and winforms.

To understand two way binding, please go through the below link.
http://www.pinfaq.com/7/how-do-two-way-data-binding-in-vb-net-winforms-with-view-model

Example:
Winforms

using System;
using System.ComponentModel;
using System.Windows.Forms;

namespace WinformsDemo
{
    public partial class frmNotifyPropertyChangedDemo : Form
    {
        CustomerInfo _customerInfo = null;
        public frmNotifyPropertyChangedDemo()
        {
            InitializeComponent();

            _customerInfo = new CustomerInfo();

            //Subscribing to property changed event in CustomerInfo object. Note: 
            //The same instance of the CustomerInfo must be used in this whole class. If we create new instance anywhere inbetween, 
            //then we need to subcribe to that object once again
            _customerInfo.PropertyChanged += _customerInfo_PropertyChanged;
        }

        void _customerInfo_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "FirstName") //If event raised by FirstName property value change
            {
                txtFirstName.Text = _customerInfo.FirstName;
            }
            else if (e.PropertyName == "LastName") //If event raised by LastName property value change
            {
                txtlastName.Text = _customerInfo.LastName;
            }
        }

        private void frmNotifyPropertyChangedDemo_Load(object sender, EventArgs e)
        {
            //Below lines will set the values in _customerInfo object. 
            //Once the value set, OnPropertyChanged method in CustomerInfo object will be called from each property.
            //So, propertychanged event will be raised 2 times. 
            //One by FirstName and the another one by LastName, because we are changing both the values
            _customerInfo.FirstName = "TFName";
            _customerInfo.LastName = "TLName";
        }
    }
}

CustomerInfo Model

using System.ComponentModel;

namespace WinformsDemo
{
    public class CustomerInfo : INotifyPropertyChanged
    {
        private string _firstName;
        public string FirstName
        {
            get
            {
                return _firstName;
            }
            set
            {
                _firstName = value;

                //Calling private method to raise PropertyChanged Event
                OnPropertyChanged("FirstName");
            }
        }

        private string _lastName;
        public string LastName
        {
            get
            {
                return _lastName;
            }
            set
            {
                _lastName = value;

                //Calling private method to raise PropertyChanged Event
                OnPropertyChanged("LastName");
            }
        }

        //Event declarion came from INotifyPropertyChanged interface
        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                //Raising the event when FirstName or LastName property value changed
                PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}
commented Oct 29, 2015 by michal (54 points)
This is a fantastic explanation.

Your answer

Preview

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.
site design / logo / content © 2013 - 2015 pinfaq.com
...