数据绑定基础
Slider:进度条
<Slider Name = "slider1"...></Slider>
<TextBox Text = "{Binding Value, ElementName = slider1}"></TextBox>
写一个数据绑定的类:
class Person
{
}
后台:
Person p1 = new Person();
txtName.DataContext = p1;
txtAge.DataContext = p1;
前端:
<TextBox Text = "{Binding Name}"
<TextBox Text = "{Binding Age}"
尽量不要直接操控控件,而是新建一个类,new一个实例,给要绑定的控件设定DataContext
txtName.DataContext = p1;
<TextBox Text = "{Binding Name}"
INotifyPropertyChanged
<TextBox TextChange
//.net内置的接口
//数据绑定会检测DataContext 是否实现了INotifyPropertyChanged
//如果实现了,就会监听PropertyChanged得知属性变化。
class Person:INotifyPropertyChanged
{
private int age;
public int Age
{
get
{
return age;
}
set
{
this.age = value;
if(PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Age"));
}
}
}