属性亦是WPF数据驱动UI理念的核心之一
自定义依赖属性
实现两个控件之间通过依赖对象中的依赖属性关联
- XAML:
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBox x:Name="tb1" Width="200" Height="30"
Grid.Row="0"/>
<TextBox x:Name="tb2" Width="200" Height="30"
Grid.Row="1"/>
-
效果图:
-
派生自依赖对象的自定义类:
快捷键 propdp
class Student : DependencyObject
{
public string Name
{
get { return (string)GetValue(NameProperty); }
set { SetValue(NameProperty, value); }
}
public static readonly DependencyProperty NameProperty =
DependencyProperty.Register("Name", typeof(string), typeof(Student));
public BindingExpressionBase SetBinding(DependencyProperty dp,
BindingBase binding)
{
return BindingOperations.SetBinding(this, dp, binding);
}
}
- 核心部分关联控件:
Student student = new Student();
student.SetBinding(Student.NameProperty, new Binding("Text") { Source = tb1 });
tb2.SetBinding(TextBox.TextProperty, new Binding("Name") { Source = student });
- 动图效果演示:
- 核心概念:
DependencyProperty 对象的创建与清册:
创建一个DependencyProperty
实例并用它的 CLR 属性和宿主类型名生成hash code
,最后把 hash code 和 DependencyProperty 实例作为Key - Value
对存入全局的、名为PropertyFromName
的 **Hashtable
**中;
这样, WPF属性系统通过 **
属性名和宿主类型名
**就可以从这个全局的 Hashtable 中检索
出对应的 DependencyProperty 实例。
最后,生成的 DependencyProperty 实例被当作返回值交还:
return dp;
自定义附加属性
附加属性的本质亦是依赖属性,在特定的场合是个属性可起作用
创建两个依赖对象,将一个附加属性附加到另一个依赖对象上
- 被附加的对象:
class Huameng : DependencyObject
{
...
}
- 拥有附加属性的依赖对象:
快捷键 propa
class Student : DependencyObject
{
public static int GetGrade(DependencyObject obj)
{
return (int)obj.GetValue(GradeProperty);
}
public static void SetGrade(DependencyObject obj, int value)
{
obj.SetValue(GradeProperty, value);
}
public static readonly DependencyProperty GradeProperty =
DependencyProperty.RegisterAttached(
"Grade",
typeof(int),
typeof(Student),
new PropertyMetadata(0)
);
}
- 测试代码:
Huameng huameng = new Huameng();
Student.SetGrade(huameng, 20);
int num = Student.GetGrade(huameng);
MessageBox.Show(num.ToString());
- 效果图:
看到这些代码我们发现和依赖属性保存值的过程别无二致 ——
值被保存在 Huameng实例的 EffectiveValueEntry 数组里;
用于在数组检索值的依赖属性(附加属性)并不以 Huameng类为宿主而是寄宿在 Student类里。