学习研究了下C#中的数据绑定。
界面显示的数据与程序内部数据绑定,当界面数据修改时候,程序内部数据也会跟随变化。
例如 预先绑定界面上的 textBox1的text 与 程序内部string变量之间的绑定,之后更改text时候,那个string变量也会随之更改,不必再多写代码。
绑定方法:
例如一个Person类,有Name、Age属性。textBox1的text要与new Person的Man的Name绑定。即
Man=new Person{Name="Jack",Age="100"};
textBox1.DataBings.Add("Text",Men,"Name");
之后、当更改界面上的textBox1中的text后,Man中的Name也会随之更改。
**********************************************
但如果更改Man的Name,界面textBox1的text并不会立即变化。
原因在于:当数据源属性即Man的Name值发生变化时,没有发出通知给DataBindings
解决办法:这个Person类继承INotifyPropertyChanged
例如:
public class Person: INotifyPropertyChanged
{
private string name;
private int age;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propName="") //使用CallerMemberName 把调用方的方法或属性名称传递给方法。
{
if(PropertyChanged!=null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
private void RaisePropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public string Name
{
get
{
return name;
}
set
{
if (value != this.name)
{
name = value;
// this.RaisePropertyChanged("Name"); //直接使用字符串"Name"比较麻烦,易出错,可使用下面两种方法
OnPropertyChanged(); //使用CallerMemberName,最方便
// this.RaisePropertyChanged(nameof(Name)); //使用nameof直接获取Name的字符串
}
}
}
public int Age
{
get
{
return age;
}
set
{
if (value != this.age)
{
age = value;
this.RaisePropertyChanged("Age");
}
}
}
}