共用方式為


如何實作相依性屬性 (WPF .NET)

本文說明如何使用 欄位來備份 Common Language Runtime (CLR) 屬性 DependencyProperty ,來實作相依性屬性。 相依性屬性支援數個進階 Windows Presentation Foundation (WPF) 屬性系統功能。 這些功能包括樣式、數據系結、繼承、動畫和預設值。 如果您想要定義的屬性來支持這些功能,請將屬性實作為相依性屬性。

範例

下列範例示範如何藉由呼叫 Register 方法來註冊相依性屬性。 方法會RegisterDependencyProperty傳回稱為相依性屬性標識符的實例。 標識元會儲存在 static readonly 欄位中,並保留相依性屬性的名稱和特性。

識別元欄位必須遵循命名慣例 <property name>Property。 例如,如果您使用名稱 Location註冊相依性屬性,則識別符字段應該命名為 LocationProperty。 如果您無法遵循此命名模式,則 WPF 設計工具可能無法正確報告屬性,而且屬性系統樣式應用程式的各個層面可能無法如預期般運作。

在下列範例中, 相依性屬性的名稱及其CLR存取子是 HasFish,因此識別元欄位的名稱會命名為 HasFishProperty。 相依性屬性類型是 Boolean ,而註冊相依性屬性的擁有者類型為 Aquarium

您可以指定相依性屬性的預設 元資料 。 本範例會設定相依性屬性的 HasFish 預設值false

public class Aquarium : DependencyObject
{
    public static readonly DependencyProperty HasFishProperty =
        DependencyProperty.Register(
            name: "HasFish",
            propertyType: typeof(bool),
            ownerType: typeof(Aquarium),
            typeMetadata: new FrameworkPropertyMetadata(defaultValue: false));

    public bool HasFish
    {
        get => (bool)GetValue(HasFishProperty);
        set => SetValue(HasFishProperty, value);
    }
}
Public Class Aquarium
    Inherits DependencyObject

    Public Shared ReadOnly HasFishProperty As DependencyProperty =
    DependencyProperty.Register(
        name:="HasFish",
        propertyType:=GetType(Boolean),
        ownerType:=GetType(Aquarium),
        typeMetadata:=New FrameworkPropertyMetadata(defaultValue:=False))

    Public Property HasFish As Boolean
        Get
            Return GetValue(HasFishProperty)
        End Get
        Set(value As Boolean)
            SetValue(HasFishProperty, value)
        End Set
    End Property

End Class

如需如何及為何實作相依性屬性的詳細資訊,而不是只支援具有私用字段的 CLR 屬性,請參閱 相依性屬性概觀

另請參閱