方法: 依存関係プロパティの所有者の種類を追加する

この例では、別の型に登録されている依存関係プロパティの所有者としてクラスを追加する方法を示します。 これにより、WPF XAML リーダーとプロパティ システムの両方で、クラスがプロパティの追加所有者として認識されるようになります。 所有者として追加すると、追加されたクラスで型固有のメタデータを提供できるようになります。

次の例では、StatePropertyMyStateControl クラスによって登録されるプロパティです。 クラス 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

関連項目