WPF引入了一种新的属性:Dependency属性。Dependency属性的应用贯串在整个WPF当中。Dependency属性根据多个提供对象来决定它的值。并且是及时更新的。提供对象可以是动画,不断地改变它的值。也可以是父元素,它的属性值被继承到子元素。毫无疑问,Dependency属性最大的特点就是内建的变化通知功能。提供Dependency属性功能主要是为了直接从声明标记提供丰富的功能。WPF声明的友好设计的关键是大量的使用属性。如果没有Dependency属性,我们将不得不编写大量的代码。关于WPF的Dependency属性,我们将重点研究如下三个方面:
1、变化通知功能:属性的值被改变后,通知界面进行更新。
2、属性值的继承功能:子元素将继承父元素中对应属性名的值。
3、支持多个提供对象:我们可以通过多种方式来设置Dependency属性的值。
public
class
TestDependencyProperty:DependencyObject

...
{
public static readonly DependencyProperty IsDefaultProperty;
static Button btn = null;

static TestDependencyProperty()

...{
TestDependencyProperty.IsDefaultProperty =
DependencyProperty.Register("IsDefault", typeof(bool), typeof(TestDependencyProperty)
, new FrameworkPropertyMetadata(false, new PropertyChangedCallback(OnIsDefaultChanged)));
}

public TestDependencyProperty(Button b)

...{
btn = b;
}

public bool IsDefault

...{

get ...{ return (bool)GetValue(TestDependencyProperty.IsDefaultProperty); }

set ...{ SetValue(TestDependencyProperty.IsDefaultProperty,value); }
}

private static void OnIsDefaultChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)

...{
if (btn != null)

...{
if ((bool)e.NewValue)
btn.Background = new SolidColorBrush(Color.FromArgb(255, 65, 0, 0));
else
btn.Background = new SolidColorBrush(Color.FromArgb(255,0, 0, 222));
}
}
}