When a property is binded to UI element, and if the property value changes , if you want to reflect the changed value on the binded UI element, you have make sure the property containing class should implement INotifyPropertyChanged inteface.
In the below example, TextBox text property is binded with “Grade” property of Student Class.
if Student Class , Grade property is changed to new value it should reflect on the grade textbox of the below figure
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | using System; using System.ComponentModel; using System.Windows.Forms; namespace PropertyChangeNotification { //Student class implements INotifyPropertyChanged interface class Student : INotifyPropertyChanged { private string name; public string Name { get { return name; } set { name = value; } } private string grade; public string Grade { get { return grade; } set { if (value != Grade) { grade = value; //Whenever property value is changes //PropertyChanged event is triggered OnPropertyChanged("Grade"); } } } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; //Create OnPropertyChanged method to raise event protected void OnPropertyChanged(string PropertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(PropertyName)); } #endregion } //Form Class public partial class Form1 : Form { //Create instanct to bind Student MyStudent = new Student { Name = "John", Grade = "B" }; public Form1() { InitializeComponent(); tbName.Text = MyStudent.Name; //Binding the Textbox text property and student class Grade property tbGrade.DataBindings.Add(new Binding("Text", MyStudent, "Grade")); } private void btnUpdateGrade_Click(object sender, EventArgs e) { //When ever property values is changes, property change notificaiton is triggered and //new value will be updated on to Textbox. MyStudent.Grade = "D"; } } } |
Source Code: Download
How do you implement property change notifications?,
How do you raise property to change events?,
How will an object be notified if the property bound to it has been changed?,
What is property changed?,