C# - INotifyPropertyChanged

When a property of an object changes its value and that object implements INotifyPropertyChanged, it can raise the PropertyChanged event. Elemtns which belongs to UI are bound to that property, they can then automatically update themselves to reflect the new value.

Example:

Here's a simple example of a class named Person that implements INotifyPropertyChanged:


using System;
using System.ComponentModel;

public class Person : INotifyPropertyChanged
{
    private string _name;
    private int _age;

    public string Name
    {
        get { return _name; }
        set
        {
            if (_name != value)
            {
                _name = value;
                OnPropertyChanged(nameof(Name));
            }
        }
    }

    public int Age
    {
        get { return _age; }
        set
        {
            if (_age != value)
            {
                _age = value;
                OnPropertyChanged(nameof(Age));
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

class Program
{
    static void Main(string[] args)
    {
        Person person = new Person();

        // Subscribe to property changed event
        person.PropertyChanged += Person_PropertyChanged;

        // Set properties
        person.Name = "Alice";
        person.Age = 30;

        Console.ReadLine();
    }

    private static void Person_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        Console.WriteLine($"Property '{e.PropertyName}' changed.");
    }
}

Explanation:

  1. The class Person implements the INotifyPropertyChanged interface.
  2. Two private fields, _name and _age, are backed by properties Name and Age.
  3. Whenever the Name or Age properties are set with a new value, the OnPropertyChanged method is called with the name of that property.
  4. The OnPropertyChanged method then raises the PropertyChanged event if there are any subscribers.
  5. Whenever these properties are changed, the Person_PropertyChanged method gets triggered, and it prints a message indicating which property has changed.

The output will be:


Property 'Name' changed.
Property 'Age' changed.

This demonstrates how the PropertyChanged event works in the Person class, notifying when specific properties are modified.

When you use the INotifyPropertyChanged interface, any changes in the data below are quickly shown in the user interface without having to update it yourself. This idea is crucial in the MVVM (Model-View-ViewModel) pattern used a lot in .NET apps to keep business logic, UI, and data apart.

INotifyPropertyChanged Best Practices:

INotifyPropertyChanged is vital for updating user interfaces when data changes in C#. Here are some best practices to make it work smoothly:

  1. Clear Property Naming:

    • Name properties and their corresponding event with clarity.

      
      private string _name;
      public string Name
      {
          get { return _name; }
          set
          {
              if (_name != value)
              {
                  _name = value;
                  OnPropertyChanged(nameof(Name));
              }
          }
      }
                
  2. Property Validation:

    • Validate data before assigning it to properties to maintain data integrity.

      
      private int _age;
      public int Age
      {
          get { return _age; }
          set
          {
              if (value >= 0 && value <= 120) // Example validation
              {
                  _age = value;
                  OnPropertyChanged(nameof(Age));
              }
              // Handle invalid age input here
          }
      }
                
  3. OnPropertyChanged Method:

    • Invoke the PropertyChanged event after the property value changes.

      
      protected void OnPropertyChanged(string propertyName)
      {
          PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
      }
      
                
  4. Granular Property Changes:

    • Raise PropertyChanged events for specific properties.

      
      private string _address;
      public string Address
      {
          get { return _address; }
          set
          {
              if (_address != value)
              {
                  _address = value;
                  OnPropertyChanged(nameof(Address));
              }
          }
      }
      
                
  5. Using INotifyPropertyChanged in Class:

    • Raise PropertyChanged events for specific properties.

      
      public class Person : INotifyPropertyChanged
      {
          public event PropertyChangedEventHandler PropertyChanged;
          // Other properties and methods here
      }
                

These practices ensure smooth and efficient UI updates when using INotifyPropertyChanged in C#.