数据源是一个对象,一个对象可以有很多的元素,这些对象通过属性展示给外界。对于UI上的元素某个属性值的变化,由Binding送达的属性叫做Binding的Path(路径)。在做一个属性具有通知Binding值已经变化的能力,通过实现INotifyPropertyChanged接口,属性值变化是会通知Binding端元素的UI,属性已经发生变化,并在UI中显示新的值。Binding设置了数据源后,会自动监听INotifyPropertyChanged事件。
class Student : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string name;
public string Name
{
get { return name; }
set
{
name = value;
if (PropertyChanged != null)
{
//执行通知属性已经发生改变
this.PropertyChanged.Invoke(this,new PropertyChangedEventArgs("Name"));
}
}
}
}
this.txtbox5.SetBinding(TextBox.TextProperty, new Binding("Name") { Source = student = new Student() });
TextBox的UI元素的基类FrameworkElement有针对BindingOperations.SetBinding(...)进行装(SetBinding)。当student.name这个属性变化更新时,TextBox也会跟着变化更新。