依賴屬性
".NET properties are nothing more than syntactic sugar over set and get methods."
我們知道.NET的屬性隻不過是get/set方法的文法糖衣。
"Dependency properties are the workhorse of WPF. This infrastructure provides for many of WPF's features, such as data binding, animations, and visual inheritance. In fact, most of the various element properties are Dependency Properties. Sometimes we need to create such properties for our own controls or windows."
依賴屬性這個基礎架構為我們提供了實作WPF諸多特性的基礎,如資料綁定、動畫等。
DependencyObject和DependencyPorperty兩個類是WPF屬性系統的核心。DependencyObject是WPF系統中相當底層的一個基類,如下:

從這顆繼承樹可以看出,WPF的所有UI控件都是依賴對象。WPF的類庫在設計時充分利用了依賴屬性的優勢,UI空間的絕大多數屬性都已經依賴化了。
有些時候,我們需要為我們自定義的類或控件等添加依賴屬性。
DebugLZQ前面的博文:
WPF 自定義依賴屬性介紹了如何為自定義的類添加依賴屬性;這篇博文以前面的博文為基礎,介紹如何為User Control添加Dependency Property。
為User Control添加依賴屬性
1.首先定義一個名為SimpleControl的UserControl;在SimpleControl.xaml.cs中鍵入"propdp"
連按2次Tab,修改依賴屬性名為YearPublishedProperty,屬性包裝名為YearPublished,預設值為2013。最終如下:
public int YearPublished
{
get { return (int)GetValue(YearPublishedProperty); }
set { SetValue(YearPublishedProperty, value); }
}
public static readonly DependencyProperty YearPublishedProperty =
DependencyProperty.Register("YearPublished", typeof(int), typeof(SimpleControl), new PropertyMetadata(2013));
2.為了能在XAML中使用,添加這個映射
<Window x:Class="CreatingADependencyProperty.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:CreatingADependencyProperty"
我們用Binding使用如下:
<StackPanel>
<local:SimpleControl x:Name="_simple"/>
<TextBlock Text="{Binding YearPublished,ElementName=_simple}" FontSize="30"/>
<Button Content="Change Value" FontSize="20" Click="OnChangeValue"/>
</StackPanel>
Click事件如下
private void OnChangeValue(object sender, RoutedEventArgs e)
{
_simple.YearPublished++;
}
程式運作如下:
點選幾次button