WPF 作为一个专门的展示层技术,让程序员专注于逻辑层,让展示层永远处于逻辑层的从属地位;
这主要因为有 DataBinding 和配套的 Dependency Property 和 DataTemplate;
1. 数据更新提醒
Binding 是一种自动机制,当属性的值变化后属性要有能力通知 Binding,让 Binding 把变化传递给 UI 元素。
class Student : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
if (PropertyChanged != null)
{
this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Name"));
}
}
}
}
BindingOperations.SetBinding(this.textboxName, TextBox.TextProperty,
new Binding() { Source = new Student(), Path = new PropertyPath("Name") }
);
//FramewordElement 对 BindingOperations.SetBinding 进行了封装,且 Binding 实例化时接受传入 Path,故:
this.textboxName.SetBinding(TextBox.TextProperty, new Binding("Name") { Source = new Student() });