Files
06-Note/WPF/DependencyProperty.md

39 lines
1.4 KiB
Markdown
Raw Normal View History

2023-06-20 09:22:53 +08:00
# 依赖属性
- 节省实例对内存的开销
- 属性值可以通过Binding依赖在其他对象上
- 本身没有值依赖Binding数据源获取值
- 依赖属性需要依托依赖对象作为宿主
- WPF的所有控件均是依赖对象绝大多数属性也均为依赖属性
定义依赖属性
DependencyProperty是一种类型所有的依赖属性都是这个类型并且被public static readonly
```csharp
public class Student:DependencyObject
{
public static readonly DependencyProperty NameProperty=DependencyProperty.Register("Name",typeof(string),typeof(Student))
//PropertyMetadata
//CoerceValueCallback 依赖属性值被强制改变,调用此委托,关联一个影响函数
//DefaultValue 依赖属性未被显式赋值时,若读取则获取此默认值,不设置会抛出异常
//IsSealed 控制该数值是否可以更改默认true
//PropertyChangedCallback依赖属性的值被改变后此委托被调用关联一个影响函数
//clr属性包装依赖属性
public string Name
{
get{return (string)GetValue(NameProperty)}
Set{SetValue(NameProperty,value)}
}
public BindingExpressionBase SetBinding(DependencyProperty dp,BindingBase binding)
{
return BindingOperations.SetBinding(this,dp,binding)
}
}
Student stu=new Student()
stu.SetValue(Student.NameProperty,this.textBox.Text)
textBox1.Text=(string)stu.GetValue(Student.NameProperty)
```