Implement Change Notification Using INotifyPropertyChanged in WPF

INotifyPropertyChanged was introduced in .NET 2.0. This interface has only one member, the PropertyChanged event that will notify listeners when a property of the implementing class is changed.

Demo

  • Open Visual Studio and select WPF application.
  • Open/add one user control or window.
  • Create one normal property, here I have added FirstName as in the following:
    1. private string firstname = string.Empty;  
    2.   
    3.         public string FristName  
    4.         {  
    5.             get { return firstname; }  
    6.             set  
    7.             {  
    8.                 firstname = value;  
    9.              
    10.             }  
    11.  }  
  • Add the same property into two controls as in the following:
    1. <TextBlock Margin="2">First Name</TextBlock>  
    2. <TextBox Margin="2" Grid.Row="0" Grid.Column="1" MinWidth="120" Text="{Binding Path=FristName,ElementName=ThisControl,UpdateSourceTrigger=PropertyChanged}"></TextBox>  
    3. <TextBlock Margin="2" Grid.Column="2" Text="{Binding Path=FristName,ElementName=ThisControl,UpdateSourceTrigger=PropertyChanged}"></TextBlock>  
  • Run the application, I entered the first name field but not displaying in my TextBlock in the right side.





  • But we can see the property change in the preceding picture. But it's not reflecting it in the UI.
  • Implement the INotifyPropertyChanged interface, no change in the XAML.
    1. public partial class INotify : UserControl, INotifyPropertyChanged  
    2.   
    3.  public INotify()  
    4.  {  
    5.      InitializeComponent();  
    6.  }  
    7.   
    8.  private string firstname = string.Empty;  
    9.   
    10.  public string FristName  
    11.  {  
    12.      get { return firstname; }  
    13.      set  
    14.      {  
    15.          firstname = value;  
    16.          OnPropertyChanged("FristName");  
    17.      }  
    18.  }  
    19.   
    20.  
    21.  #region INotifyPropertyChanged Members  
    22.   
    23.  public event PropertyChangedEventHandler PropertyChanged;  
    24.  public void OnPropertyChanged(string txt)  
    25.  {  
    26.   
    27.      PropertyChangedEventHandler handle = PropertyChanged;  
    28.      if (handle != null)  
    29.      {  
    30.          handle(thisnew PropertyChangedEventArgs(txt));  
    31.      }  
    32.  }  
    33.  #endregion  
  • Run the application and see the change.


  • We got the change in the UI.

Conclusion

The INotifyPropertyChanged interface will notify the source of changes to the target.

Up Next
    Ebook Download
    View all
    Learn
    View all