如何:加入相依性屬性的擁有者類型
這個範例示範如何將類別新增為為不同類型註冊之相依性屬性的擁有者。 如此一來,WPF XAML 讀取器和屬性系統都能夠將類別辨識為屬性的其他擁有者。 新增為擁有者選擇性地允許新增類別提供類型特定的中繼資料。
在下列範例中, StateProperty
是 類別 MyStateControl
所註冊的屬性。 類別 UnrelatedStateControl
會使用 方法將本身新增為 擁有者 StateProperty
AddOwner ,特別是使用簽章,允許相依性屬性的新中繼資料,因為它存在於新增類型上。 請注意,您應該為屬性提供 Common Language Runtime (CLR) 存取子,類似于實作相依性屬性 範例中顯示的 範例,以及重新公開要新增為擁有者之類別的相依性屬性識別碼。
如果沒有包裝函式,相依性屬性仍會從使用 GetValue 或 SetValue 的程式設計存取觀點運作。 但您通常想要將這個屬性系統行為與 CLR 屬性包裝函式平行處理。 包裝函式可讓您更輕鬆地以程式設計方式設定相依性屬性,並讓屬性設定為 XAML 屬性。
若要瞭解如何覆寫預設中繼資料,請參閱 覆寫相依性屬性 的中繼資料。
範例
public class MyStateControl : ButtonBase
{
public MyStateControl() : base() { }
public Boolean State
{
get { return (Boolean)this.GetValue(StateProperty); }
set { this.SetValue(StateProperty, value); }
}
public static readonly DependencyProperty StateProperty = DependencyProperty.Register(
"State", typeof(Boolean), typeof(MyStateControl),new PropertyMetadata(false));
}
Public Class MyStateControl
Inherits ButtonBase
Public Sub New()
MyBase.New()
End Sub
Public Property State() As Boolean
Get
Return CType(Me.GetValue(StateProperty), Boolean)
End Get
Set(ByVal value As Boolean)
Me.SetValue(StateProperty, value)
End Set
End Property
Public Shared ReadOnly StateProperty As DependencyProperty = DependencyProperty.Register("State", GetType(Boolean), GetType(MyStateControl),New PropertyMetadata(False))
End Class
public class UnrelatedStateControl : Control
{
public UnrelatedStateControl() { }
public static readonly DependencyProperty StateProperty = MyStateControl.StateProperty.AddOwner(typeof(UnrelatedStateControl), new PropertyMetadata(true));
public Boolean State
{
get { return (Boolean)this.GetValue(StateProperty); }
set { this.SetValue(StateProperty, value); }
}
}
Public Class UnrelatedStateControl
Inherits Control
Public Sub New()
End Sub
Public Shared ReadOnly StateProperty As DependencyProperty = MyStateControl.StateProperty.AddOwner(GetType(UnrelatedStateControl), New PropertyMetadata(True))
Public Property State() As Boolean
Get
Return CType(Me.GetValue(StateProperty), Boolean)
End Get
Set(ByVal value As Boolean)
Me.SetValue(StateProperty, value)
End Set
End Property
End Class
另請參閱
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應