在我刚刚开始接触到WPF的DependencyProperty的时候,仅仅觉得是一个很巧妙的实现,随着学习WPF的深入,也来越觉得DependencyProperty其实是WPF的核心技术点之一。
DependencyProperty和DependencyObject配合,提供了WPF中基本的数据存储、访问和通知的机制。也正是因为这两个东西的存在,使得XAML,Binding,Animation都成为可能。
让我们来看一下重新实现后的数据层。
using System;
using System.Windows;
using System.Windows.Media;
namespace ColorPicker2
{
public class ColorPickerData : DependencyObject
{
public ColorPickerData()
{
}
public static DependencyProperty BackgroundProperty = DependencyProperty.Register(
"Background",
typeof(Brush),
typeof(ColorPickerData),
new PropertyMetadata(new SolidColorBrush(Colors.Black))
);
public static DependencyProperty RedProperty = DependencyProperty.Register(
"Red",
typeof(byte),
typeof(ColorPickerData)
);
public static DependencyProperty GreenProperty = DependencyProperty.Register(
"Green",
typeof(byte),
typeof(ColorPickerData)
);
public static DependencyProperty BlueProperty = DependencyProperty.Register(
"Blue",
typeof(byte),
typeof(ColorPickerData)
);

public Brush Background
{
get { return (Brush)GetValue(BackgroundProperty); }
set { SetValue(BackgroundProperty, value); }
}
public byte Red
{
get { return (byte)GetValue(RedProperty); }
set { SetValue(RedProperty, value); }
}
public byte Green
{
get { return (byte)GetValue(GreenProperty); }
set { SetValue(GreenProperty, value); }
}
public byte Blue
{
get { return (byte)GetValue(BlueProperty); }
set { SetValue(BlueProperty, value); }
}
protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
{
if (e.Property.Equals(RedProperty) ||
e.Property.Equals(GreenProperty) ||
e.Property.Equals(BlueProperty))
{
this.Background = new SolidColorBrush(Color.FromRgb(this.Red, this.Green, this.Blue));
}
base.OnPropertyChanged(e);
}
}
}
在行12-35,我们注册了4个DependencyProperty:RedProperty, GreenProperty, BlueProperty 和 BackgroundProperty。我们也不再使用成员字段去保存这些属性的具体值。而是直接使用DependencyObject上的GetValue和SetValue方法设置和读取值。
http://www.haogongju.net/art/356014