如何:註冊附加屬性

這個範例示範如何註冊附加屬性並提供公用存取子,讓您可以在 XAML 和程式碼中使用 屬性。 附加屬性是由 XAML 定義的語法概念。 WPF 類型的大部分附加屬性也會實作為相依性屬性。 您可以在任何 DependencyObject 類型上使用相依性屬性。

範例

下列範例示範如何使用 方法,將附加屬性註冊為相依性屬性 RegisterAttached 。 提供者類別可以選擇提供在另一個類別上使用屬性時所適用屬性的預設中繼資料,除非該類別會覆寫中繼資料。 在此範例中,IsBubbleSource 屬性的預設值設定為 false

附加屬性的提供者類別 (即使未註冊為相依性屬性也是一樣) 必須提供遵循命名慣例 Set[AttachedPropertyName]Get[AttachedPropertyName] 的靜態 get 和 set 存取子。 這些存取子是必要的,讓代理 XAML 讀取器可以將屬性辨識為 XAML 中的屬性,並解析適當的類型。

public static readonly DependencyProperty IsBubbleSourceProperty = DependencyProperty.RegisterAttached(
  "IsBubbleSource",
  typeof(Boolean),
  typeof(AquariumObject),
  new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.AffectsRender)
);
public static void SetIsBubbleSource(UIElement element, Boolean value)
{
  element.SetValue(IsBubbleSourceProperty, value);
}
public static Boolean GetIsBubbleSource(UIElement element)
{
  return (Boolean)element.GetValue(IsBubbleSourceProperty);
}
Public Shared ReadOnly IsBubbleSourceProperty As DependencyProperty = DependencyProperty.RegisterAttached("IsBubbleSource", GetType(Boolean), GetType(AquariumObject), New FrameworkPropertyMetadata(False, FrameworkPropertyMetadataOptions.AffectsRender))
Public Shared Sub SetIsBubbleSource(ByVal element As UIElement, ByVal value As Boolean)
    element.SetValue(IsBubbleSourceProperty, value)
End Sub
Public Shared Function GetIsBubbleSource(ByVal element As UIElement) As Boolean
    Return CType(element.GetValue(IsBubbleSourceProperty), Boolean)
End Function

另請參閱