共用方式為


HOW TO:註冊附加屬性

本範例顯示如何註冊附加屬性並提供公用存取子,以便在Extensible Application Markup Language (XAML) 和程式碼中都可以使用該屬性。 附加屬性是Extensible Application Markup Language (XAML) 所定義的語法概念。 WPF 型別的大部分附加屬性也會以相依性屬性的方式實作。 您可以在任何 DependencyObject 型別上使用相依性屬性。

範例

下列範例顯示如何藉由使用 RegisterAttached 方法,將附加屬性註冊為相依性屬性。 提供者類別有個選項可以提供屬性的預設中繼資料,適用於在其他類別上使用屬性時,除非類別會覆寫中繼資料。 在本範例中,IsBubbleSource 屬性的預設值會設為 false。

附加屬性 (Property) 的提供者類別 (即使未註冊成相依性屬性 (Property)) 必須提供遵循命名慣例 Set[AttachedPropertyName] 和 Get[AttachedPropertyName] 的靜態 get 和 set 存取子。這些存取子是必要的,才能讓作用的 XAML 讀取器將屬性 (Property) 辨認為 XAML 的屬性 (Attribute) 並解析適當的型別。 

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
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);
}

請參閱

參考

DependencyProperty

概念

相依性屬性概觀

自訂相依性屬性

其他資源

屬性 HOW TO 主題