HOW TO:加入相依性屬性的擁有者型別
更新:2007 年 11 月
本範例顯示如何加入類別做為針對其他型別而註冊的相依性屬性的擁有者。藉由進行這項作業,WPFXAML 讀取器和屬性系統都能夠將類別辨識為屬性的額外擁有者。加入做為擁有者會選擇性允許加入的類別提供型別專有的中繼資料。
下列範例中的 StateProperty 是 MyStateControl 類別所註冊的屬性。類別 UnrelatedStateControl 會使用 AddOwner 方法,將自身加入做為 StateProperty 的擁有者,特別會使用簽章允許相依性屬性的新中繼資料,因為它存在於加入的型別上。請注意,您應該要提供屬性的 Common Language Runtime (CLR) 存取子,類似 HOW TO:實作相依性屬性範例所示,以及在要加入做為擁有者的類別上重新公開相依性屬性識別項。
在沒有包裝函式的情況下,相依性屬性 (Property) 還是會使用 GetValue 或 SetValue,從程式設計存取方面運作。但您通常會希望讓這個屬性 (Property) 系統行為與 CLR 屬性 (Property) 包裝函式一致。包裝函式可以讓您輕鬆以程式設計方式設定相依性屬性 (Property),並可以讓屬性 (Property) 設定為 XAML 屬性 (Attribute)。
若要知道如何覆寫預設中繼資料,請參閱 HOW TO:覆寫相依性屬性的中繼資料。
範例
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 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); }
}
}