如何:註冊附加屬性
這個範例示範如何註冊附加屬性並提供公用存取子,讓您可以在 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
另請參閱
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應