如何:加入相依性屬性的擁有者類型
這個範例顯示如何將類別新增為為不同類型註冊之相依性屬性的擁有者。 如此一來,WPF XAML 讀取器和屬性系統都能夠將類別辨識為屬性的其他擁有者。 新增為擁有者能選擇性地允許新增類別提供類型特定的中繼資料。
在下列範例中, StateProperty
是 MyStateControl
類別所註冊的屬性。 類別 UnrelatedStateControl
使用 AddOwner 方法將本身新增為 StateProperty
的擁有者,特別是使用簽章,其允許相依性屬性的新中繼資料,因為它存在於新增類型上。 請注意,您應該提供與 實作相依性屬性 範例中所示之屬性的通用語言執行平台 (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