一、概述
依赖属性指属性没有值,通过Binding从数据源中获取值
二、使用
2.1 依赖属性 Register
public class Student0:DependencyObject
{
public string Name
{
get {
return (string)GetValue(NameProperty);
}
set
{
SetValue(NameProperty, value);
}
}
public static readonly DependencyProperty NameProperty = DependencyProperty.Register("Name", typeof(string), typeof(Student0));
public BindingExpressionBase SetBinding(DependencyProperty dp, BindingBase bind)
{
return BindingOperations.SetBinding(this,dp,bind);
}
}
stu = new Student0();
Binding bind = new Binding("Text") { Source=textBox1};
stu.SetBinding(Student0.NameProperty, bind);
textBox2.SetBinding(TextBox.TextProperty, new Binding("Name") { Source=stu});
2.2 附加属性 RegisterAttached
public class Human:DependencyObject
{
}
public class School : DependencyObject
{
public static int GetGrade(DependencyObject obj)
{
return (int)obj.GetValue(GradeProperty);
}
public static void SetGrade(DependencyObject obj, int value)
{
obj.SetValue(GradeProperty, value);
}
// Using a DependencyProperty as the backing store for Grade. This enables animation, styling, binding, etc...
public static readonly DependencyProperty GradeProperty =
DependencyProperty.RegisterAttached("Grade", typeof(int), typeof(School), new UIPropertyMetadata(0));
}
Human human = new Human();
School.SetGrade(human, 15);
int grade = School.GetGrade(human);
MessageBox.Show(grade.ToString());