この例では、別の型に登録されている依存関係プロパティの所有者としてクラスを追加する方法を示します。 これにより、WPF XAML リーダーとプロパティ システムはどちらも、クラスをプロパティの追加の所有者として認識できます。 必要に応じて、所有者として追加すると、クラスを追加して型固有のメタデータを提供できます。
次の例では、 StateProperty は MyStateControl クラスによって登録されたプロパティです。
UnrelatedStateControlクラスは、StateProperty メソッドを使用してAddOwnerの所有者として自分自身を追加します。具体的には、追加する型に存在する依存関係プロパティの新しいメタデータを許可するシグネチャを使用します。 依存関係プロパティの 実装 の例に示されている例のようなプロパティに共通言語ランタイム (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
こちらも参照ください
- カスタム依存関係プロパティ
- 依存関係プロパティの概要
.NET Desktop feedback