To learn databinding I have a test-project with copied example code. I have a test class with some properties and on a form I have some textboxes, that should be two-way bound to the class properties:
public class Test : INotifyPropertyChanged
{
private string strProp1;
private string strProp2;
public string StrProp1
{
get {return strProp1; }
//set { strProp1 = value; OnPropertyChanged("StrProp1"); }
set { strProp1 = value; OnPropertyChanged(); }
}
public string StrProp2
{
get { return strProp2; }
set { strProp2 = value; OnPropertyChanged(); }
}
///.... more properties
//---------------------------------
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
//// in Form class and Load() ////
Test tst=new Test();
txt1.DataBindings.Add("Text", tst, "StrProp1", true, DataSourceUpdateMode.OnPropertyChanged);
txt2.DataBindings.Add("Text", tst, "StrProp2", true, DataSourceUpdateMode.OnPropertyChanged);
Now, when I edit only textbox txt2 I see with the debugger that following code/calls are made:
- set { strProp2... // OK
- OnPropertyChanged() // OK
- getters of all properties // unnecessary?
- OnPropertyChanged() // unnecessary, second time. Why is that?
- getters of all properties // unnecessary, second time!
I don't understand the bindings fully, yet. What is my coding error? Is there a better way to do two-way binding? OnPropertyChanged(): why creating every time handler = PropertyChanged? What purpose has propertyName in PropertyChangedEventArgs(propertyName))? It is not used anyway? Thanks for help / advice.
Databinding do updates only on necessary properties, without double call to all the class getters.
databinding is usefull with Tables here is an example
Click Here to show