共用方式為


如何:實作相依性屬性

此範例示範如何使用 欄位來備份 Common Language Runtime (CLR) 屬性 DependencyProperty ,從而定義相依性屬性。 當您定義自己的屬性,並想要它們支援 Windows Presentation Foundation (WPF) 功能的許多層面,包括樣式、資料系結、繼承、動畫和預設值時,您應該將它們實作為相依性屬性。

範例

下列範例會先呼叫 Register 方法來註冊相依性屬性。 您用來儲存相依性屬性名稱和特性的識別碼欄位名稱,必須是 Name 您在呼叫中為相依性屬性 Register 選擇的名稱,並附加常值字串 Property 。 例如,如果您使用 的 Location 註冊相依性屬性 Name ,則您為相依性屬性定義的識別碼欄位必須命名為 LocationProperty

在此範例中,相依性屬性的名稱及其 CLR 存取子是 ;識別碼欄位為 StateStateProperty ;屬性的類型為 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 屬性,請參閱 相依性屬性概觀

另請參閱