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

此示例演示如何将类添加为针对不同类型注册的依赖性属性的所有者。 通过执行此操作,WPF XAML 读取器和属性系统都可以将该类识别为属性的其他所有者。 添加所有者时,也可以选择添加类来提供类型特定的元数据。

在下面的示例中,StateProperty 是由 MyStateControl 类注册的属性。 类 UnrelatedStateControl 使用 AddOwner 方法将本身添加为 StateProperty 的所有者,当添加类型上存在依赖项属性时,则专门使用依赖项属性的新元数据允许的签名。 请注意,对于与如何:实现依赖项属性示例中所示的示例类似的属性,应提供common language runtime (CLR) 访问器,并在要添加为所有者的类上重新公开依赖项属性标识符。

未使用包装时,从使用 GetValueSetValue 的程序访问的角度来看,依赖项属性仍将有效。 但是,您通常需要将此属性系统的行为与 CLR 属性包装并行处理。 包装使以编程方式对依赖项属性进行设置的操作更加容易,并可以将属性设置为 XAML 特性。

若要了解如何重写默认元数据,请参见如何:重写依赖项属性的元数据

示例

  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
      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
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); }
  }
}

请参见

概念

自定义依赖项属性

依赖项属性概述