在WPF下学习的数据绑定,首先需要新建一个类,用于与界面的值相对应。例如定义一个Person类
class person
{
public string Name
{
get;
set;
}
public int Age
{
get;
set;
}
}
然后在界面上添加两个textBox,分别对应Name,Age,在xaml里添加Binding,即在两个textBox的代码中分别写上Text="{BindingName}" Text="{BindingAge}"
<TextBox x:Name="txtName" Text="{Binding Name}" HorizontalAlignment="Left" Height="23" Margin="45,45,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
<TextBox x:Name="txtAge" Text="{Binding Age}" HorizontalAlignment="Left" Height="23" Margin="45,95,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
之后添加Loaded事件,
private void MyLoaded(object sender, RoutedEventArgs e)
{
p1.Age = 18;
p1.Name = "Mark";
txtAge.DataContext = p1;
txtName.DataContext = p1;
}
DataContext 是连接映射的所有实体的源。 它会跟踪你对所有检索到的实体所做的更改,并且保留一个“标识缓存”,该缓存确保使用同一对象实例表示多次检索到的实体。
这样就不需要再用原始的txtAge.text="Mark",因为他的维护会很困难(大项目中)。
可是p1.Age发生改变的时候,界面上的txtAge并没有发生改变,所以需要监听空间,需要接口INotifyPropertyChanged来实现。类Person的定义需要更改
class person:INotifyPropertyChanged
{
private int age;
private string name;
public string Name
{
get
{
return name;
}
set
{
this.name = value;
if (PropertyChanged!=null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Name"));
}
}
}
public int Age
{
get
{
return age;
}
set
{
this.age = value;
if (PropertyChanged!=null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Age")) ;
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
这样就可以实现界面、后台同步改变