在我刚刚开始接触到WPF的DependencyProperty的时候,仅仅觉得是一个很巧妙的实现,随着学习WPF的深入,也来越觉得DependencyProperty其实是WPF的核心技术点之一。
DependencyProperty和DependencyObject配合,提供了WPF中基本的数据存储、访问和通知的机制。也正是因为这两个东西的存在,使得XAML,Binding,Animation都成为可能。
让我们来看一下重新实现后的数据层。
1using System;
2using System.Windows;
3using System.Windows.Media;
4
5namespace ColorPicker2
6{
7 public class ColorPickerData : DependencyObject
8 {
9 public ColorPickerData()
10 {
11 }
12 public static DependencyProperty BackgroundProperty = DependencyProperty.Register(
13 "Background",
14 typeof(Brush),
15 typeof(ColorPickerData),
16 new PropertyMetadata(new SolidColorBrush(Colors.Black))
17 );
18
19 public static DependencyProperty RedProperty = DependencyProperty.Register(
20 "Red",
21 typeof(byte),
22 typeof(ColorPickerData)
23 );
24
25 public static DependencyProperty GreenProperty = DependencyProperty.Register(
26 "Green",
27 typeof(byte),
28 typeof(ColorPickerData)
29 );
30
31 public static DependencyProperty BlueProperty = DependencyProperty.Register(
32 "Blue",
33 typeof(byte),
34 typeof(ColorPickerData)
35 );
36
37
38 public Brush Background
39 {
40 get { return (Brush)GetValue(BackgroundProperty); }
41 set { SetValue(BackgroundProperty, value); }
42 }
43
44 public byte Red
45 {
46 get { return (byte)GetValue(RedProperty); }
47 set { SetValue(RedProperty, value); }
48 }
49
50 public byte Green
51 {
52 get { return (byte)GetValue(GreenProperty); }
53 set { SetValue(GreenProperty, value); }
54 }
55
56 public byte Blue
57 {
58 get { return (byte)GetValue(BlueProperty); }
59 set { SetValue(BlueProperty, value); }
60 }
61
62 protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
63 {
64 if (e.Property.Equals(RedProperty) ||
65 e.Property.Equals(GreenProperty) ||
66 e.Property.Equals(BlueProperty))
67 {
68 this.Background = new SolidColorBrush(Color.FromRgb(this.Red, this.Green, this.Blue));
69 }
70
71 base.OnPropertyChanged(e);
72 }
73 }
74}
75
在行12-35,我们注册了4个DependencyProperty:RedProperty, GreenProperty, BlueProperty 和 BackgroundProperty。我们也不再使用成员字段去保存这些属性的具体值。而是直接使用DependencyObject上的GetValue和SetValue方法设置和读取值。
http://www.haogongju.net/art/356014