依赖属性
属性依赖是一个WPF的新概念,即属性本身没有值,通过binding依赖到其他对象身上。
面向对象的设计思路是这样的:人类和人可以当作对象的抽象类和具体实例。当面对人类这个概念时,出生率,死亡率和自然增长率这些属性才有用,而吃饭,喝水还有跑步就显得不合适。而个体人这一实例不适用出生率这些属性,却适合吃喝跑步这些属性。
所以有些属性只对类适用,有些属性更适合实例。
设计上,我们把适合类的属性用设置为静态属性,把适合实例的属性设为非静态属性。因为类只有一个,它的属性也不需要多个,就如人类只有一个出生率。人有很多个,每个人吃的方式可能都不同,所以每新建一个实例,它的属性都需要创建。
但是如果某一场景需要创建无数个实例,这个实例包含众多属性。如果需要为每个属性开辟一个内存控件,那系统进程会受很大影响,所以WPF就有了依赖属性这一概念。
代码实现是这样,先创建一个类,并继承抽象类DependencyObject
public class Student : DependencyObject
{
//在公共空间内注册一个属性
public static readonly DependencyProperty NameProperty =
DependencyProperty.Register("Name",typeof(string), typeof(Student));
}
这是前端的标签
<StackPanel>
<TextBox x:Name="tb1" BorderBrush="Black" Margin="5" />
<TextBox x:Name="tb2" BorderBrush="Black" Margin="5" />
<Button Content="OK" Margin="5" Click="Button_Click" />
</StackPanel>
这是点击事件的实现,第二行代码是关键,把tb1的Text属性值set到student的NameProperty上,形成依赖。
private void Button_Click(object sender, RoutedEventArgs e)
{
Student student = new Student();
student.SetValue(Student.NameProperty,this.tb1.Text);
this.tb2.Text = (string)student.GetValue(Student.NameProperty);
}
运行后点击OK就能把tb1的数据通过实例绑到tb2
这样的写法还比较原始,当属性依赖和binding同时使用时要多写很多代码,所以写法可以改造一下
改造后写法
类里面这样改造
public static readonly DependencyProperty NameProperty =
DependencyProperty.Register("Name",typeof(string), typeof(Student));
//这样就可以用传统的点语法调用了
public string Name {
get { return (string)GetValue(Student.NameProperty); }
set { SetValue(Student.NameProperty,value); }
}
//SetBinding包装
public BindingExpressionBase SetBinding(DependencyProperty dp,BindingBase binding)
{
return BindingOperations.SetBinding(this, dp, binding);
}
构造器中这样调用
Student student = null;
public MainWindow()
{
InitializeComponent();
student = new Student();
student.SetBinding(Student.NameProperty, new Binding("Text") { Source = this.tb1 });
tb2.SetBinding(TextBox.TextProperty, new Binding("Name") { Source = student });
}
这样就将binding一起绑定了,不需要button,修改tb1直接同步tb2