如何:为依赖项属性添加所有者类型

此示例演示如何将类添加为注册为不同类型的依赖属性的所有者。 通过执行此操作,WPF XAML 读取器和属性系统都能够将类识别为属性的附加所有者。 选择性地添加为所有者让添加类可以提供特定于类型的元数据。

在以下示例中,StatePropertyMyStateControl 类注册的属性。 UnrelatedStateControl 类使用 AddOwner 方法将自身添加为 StateProperty 的所有者,特别是使用支持在添加类型上存在依赖属性的新元数据的签名。 请注意,应该为属性提供公共语言运行时 (CLR) 访问器,类似于实现依赖属性示例中所示的示例,并在作为所有者添加的类上重新公开依赖属性标识符。

从使用 GetValueSetValue 的编程访问的角度来看,在没有包装器的情况下,依赖属性仍然可以正常工作。 但通常需要将此属性系统行为与 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

另请参阅