如何註冊附加屬性 (WPF .NET)

本文說明如何註冊附加屬性並提供公用存取子,讓您透過 Extensible Application Markup Language (XAML) 和程式碼存取附加屬性。 附加屬性可讓任何 XAML 元素上設定額外的屬性/值組,即使元素在其物件模型中未定義這些額外的屬性也一樣。 額外的屬性可全域存取。 附加屬性通常定義為沒有傳統屬性包裝函式的特殊相依性屬性形式。 Windows Presentation Foundation (WPF) 類型的大部分附加屬性也會實作為相依性屬性。 您可以在任何 DependencyObject 衍生類型上建立相依性屬性。

重要

.NET 7 和 .NET 6 的桌面指南檔正在建置中。

範例

下列範例示範如何使用 方法,將附加屬性註冊為相依性屬性 RegisterAttached 。 提供者類別可以選擇在屬性中繼資料中指定預設值。 如需屬性中繼資料的詳細資訊,請參閱 相依性屬性中繼資料 。 在此範例中 HasFish ,屬性具有 Boolean 實值型別,其預設值設定為 false

附加屬性的提供者類別必須提供遵循命名慣例 Get<property name>Set<property name> 的靜態 get/set 存取子方法。 XAML 讀取器會使用 存取子來辨識附加屬性的 XAML 屬性,並將其值解析為適當的類型。 即使附加屬性未註冊為相依性屬性,這些存取子也是必要的。

public class Aquarium : UIElement
{
    // Register an attached dependency property with the specified
    // property name, property type, owner type, and property metadata.
    public static readonly DependencyProperty HasFishProperty =
        DependencyProperty.RegisterAttached(
          "HasFish",
          typeof(bool),
          typeof(Aquarium),
          new FrameworkPropertyMetadata(defaultValue: false,
              flags: FrameworkPropertyMetadataOptions.AffectsRender)
        );

    // Declare a get accessor method.
    public static bool GetHasFish(UIElement target) =>
        (bool)target.GetValue(HasFishProperty);

    // Declare a set accessor method.
    public static void SetHasFish(UIElement target, bool value) =>
        target.SetValue(HasFishProperty, value);
}
Public Class Aquarium
    Inherits UIElement

    ' Register an attached dependency property with the specified
    ' property name, property type, owner type, and property metadata.
    Public Shared ReadOnly HasFishProperty As DependencyProperty =
        DependencyProperty.RegisterAttached("HasFish", GetType(Boolean), GetType(Aquarium),
            New FrameworkPropertyMetadata(defaultValue:=False,
                flags:=FrameworkPropertyMetadataOptions.AffectsRender))

    ' Declare a get accessor method.
    Public Shared Function GetHasFish(target As UIElement) As Boolean
        Return target.GetValue(HasFishProperty)
    End Function

    ' Declare a set accessor method.
    Public Shared Sub SetHasFish(target As UIElement, value As Boolean)
        target.SetValue(HasFishProperty, value)
    End Sub

End Class

另請參閱