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

更新:2007 年 11 月

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

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

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

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

示例

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

请参见

概念

自定义的依赖项属性

依赖项属性概述