此示例演示如何将类添加为为不同类型注册的依赖属性的所有者。 通过这样做,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