此範例示範如何使用 DependencyProperty 欄位來支援通用語言執行平台 (CLR) 屬性,從而定義相依性屬性。 如果您定義自己的屬性,並想要它們支援 Windows Presentation Foundation (WPF) 功能的許多層面 (包括樣式、資料繫結、繼承、動畫和預設值),則應該將它們實作為相依性屬性。
範例
下列範例會先呼叫 Register 方法來註冊相依性屬性。 用來儲存相依性屬性之名稱和特性的識別碼欄位名稱必須是您為相依性屬性選擇為 Register 呼叫一部分的 Name,並附加常值字串 Property
。 例如,如果您使用 Location
的 Name 來註冊相依性屬性,則為相依性屬性所定義的識別碼欄位必須命名為 LocationProperty
。
在此範例中,相依性屬性的名稱和其 CLR 存取子是 State
、識別碼欄位是 StateProperty
、屬性的類型是 Boolean,而註冊相依性屬性的類型是 MyStateControl
。
如果您無法遵循這個命名模式,則設計工具不一定會正確地報告您的屬性,而且屬性系統樣式應用程式的某些方面可能無法如預期運作。
您也可以指定相依性屬性的預設中繼資料。 此範例會將 State
相依性屬性的預設值註冊為 false
。
public class MyStateControl : ButtonBase
{
public MyStateControl() : base() { }
public Boolean State
{
get { return (Boolean)this.GetValue(StateProperty); }
set { this.SetValue(StateProperty, value); }
}
public static readonly DependencyProperty StateProperty = DependencyProperty.Register(
"State", typeof(Boolean), typeof(MyStateControl),new PropertyMetadata(false));
}
Public Class MyStateControl
Inherits ButtonBase
Public Sub New()
MyBase.New()
End Sub
Public Property State() As Boolean
Get
Return CType(Me.GetValue(StateProperty), Boolean)
End Get
Set(ByVal value As Boolean)
Me.SetValue(StateProperty, value)
End Set
End Property
Public Shared ReadOnly StateProperty As DependencyProperty = DependencyProperty.Register("State", GetType(Boolean), GetType(MyStateControl),New PropertyMetadata(False))
End Class
如需如何及為何實作相依性屬性,而不是直接使用私人欄位來支援 CLR 屬性的詳細資訊,請參閱相依性屬性概觀 (部分機器翻譯)。