WPF: Implement Change Notification Using INotifyPropertyChanged Interface
Introduction
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 FirstName as in the following:
private string firstname = string.Empty;
public string FristName
{
get { return firstname; }
set
{
firstname = value;
}
}
- Add the same property into two controls as in the following:
<TextBlock Margin="2">First Name</TextBlock>
<TextBox Margin="2" Grid.Row="0" Grid.Column="1" MinWidth="120" Text="{Binding Path=FristName,ElementName=ThisControl,UpdateSourceTrigger=PropertyChanged}"></TextBox>
<TextBlock Margin="2" Grid.Column="2" Text="{Binding Path=FristName,ElementName=ThisControl,UpdateSourceTrigger=PropertyChanged}"></TextBlock>
- Run the application, enter the first name field, but not displaying in my TextBlock in the right side.
http://www.c-sharpcorner.com/UploadFile/91c28d/implement-change-notification-using-inotifypropertychanged-i/Images/first%20name.jpg
http://www.c-sharpcorner.com/UploadFile/91c28d/implement-change-notification-using-inotifypropertychanged-i/Images/first.jpg
- We can see the property change in the preceding picture. But it's not reflecting in the UI.
- Implement the INotifyPropertyChanged interface, no change in the XAML.
public partial class INotify : UserControl, INotifyPropertyChanged
public INotify()
{
InitializeComponent();
}
private string firstname = string.Empty;
public string FristName
{
get { return firstname; }
set
{
firstname = value;
OnPropertyChanged("FristName");
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string txt)
{
PropertyChangedEventHandler handle = PropertyChanged;
if (handle != null)
{
handle(this, new PropertyChangedEventArgs(txt));
}
}
#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.