依赖属性是一种可以自己没有值,并能通过使用Binding从数据源获取值(依赖在别人身上)的属性。
优点:
- 节省实例对内存的开销。
- 属性值可以通过Binding依赖在其他对象身上。
WPF的所有控件都是依赖属性。
依赖对象被DependencyObject类实现,依赖属性由DependencyProperty类实现。
DependencyObject有GetValue()、SetValue()。
GetValue():通过DependencyProperty对象获取数据。
SetValue():通过DependencyProperty对象存储值。
public object GetValue(){DependencyProperty dp}
public void setValue(DependencyProperty dp, object value){}
propdp + Tab + tab 声明依赖属性 ,继续 Tab+Tab可以修改依赖属性的各个参数。
public static readonly DependencyProperty NameProperty =
DependencyProperty.Register("Name", //属性名称
typeof(string), //属性类型
typeof(Student), //该属性所有者,即将该属性注册到那个类上
new PropertyMetadata("")); //属性默认值
eg:
public class Student:DependencyObject{
//CLR属性包装器
public string Name{
get{return (string)GetValue(NameProperty);}
set{SetValue(NameProperty, value);}
}
//依赖属性
public static readonly DependencyProperty NameProperty =
DependencyPropertyRegister("Name", typeof(string), typeof(Student));
//SetBinding包装
public BindingExpressionBase SetBinding(DependencyProperty dp,
BindingBase binding){
return BindingOperations.SetBinding(this, dp, binding);
}
}
public class Window1{
//使用Binding把Student对象关联到textBox1上,再把textBox2关联到Student对象上形成Binding链。
public Window1(){
InitializeComponent();
stu = new Student();
stu.SetBinding(Student.NameProperty, new Binding("Text"){Source = textBox1});
textBox2.SetBinding(TextBox.TextProperty, new Binding("Name"){Source = stu});
}
}