WPF依赖属性:为什么我需要指定所有者类型?

这是我注册DependencyProperty

  public static readonly DependencyProperty UserProperty = DependencyProperty.Register("User", typeof (User), typeof (NewOnlineUserNotifier)); public User User { get { return (User)GetValue(UserProperty); } set { SetValue(UserProperty, value); } } 

DependencyProperty.Register方法的第三个参数要求您指定依赖项属性所在的Control的类型(在本例中,我的用户控件称为NewOnlineUserNotifier )。

我的问题是, 为什么你实际指定了所有者的类型,如果指定的类型与实际所有者不同,会发生什么?

您调用Register方法的类型不是属性的事实所有者,因此您不能指定与实际所有者不同的类型,因为您指定的类型实际所有者。

这可能有用的一个示例是当您创建包含其他控件的自定义控件时。 以前使用WinForms,如果你有一些仅对该容器有用的额外信息,但在语义上属于孩子,那么你能做的最好的事情就是将这些信息放在hold-all“Tag”属性中。 这既消除了类型的安全性,又从未确定另一个类不会尝试在标记中存储其他内容。 现在使用WPF依赖项属性允许您将值绑定到对象,而对象本身不需要保存该值。 一个简单的例子:

 public class ButtonContainer : Control { public Button ChildButton { get; set; } public static readonly DependencyProperty FirstOwnerProperty = DependencyProperty.Register("FirstOwner", typeof(ButtonContainer), typeof(Button)); public ButtonContainer() { ChildButton = new Button(); ChildButton.SetValue(FirstOwnerProperty, this); } } 

现在按钮有一个额外的属性,只在ButtonContainer的上下文中有意义,并且只能在ButtonContainer的上下文中访问 – 就像一个类型安全的封装标签。

使用新类如下:

 ButtonContainer container1 = new ButtonContainer(); ButtonContainer container2 = new ButtonContainer(); container2.ChildButton = container1.ChildButton; 

当ChildButton从一个容器移动到另一个容器时,其FirstOwnerProperty的值随之移动,就好像它是Button类的真实成员一样。 Container2可以调用ChildButton.GetValue(FirstOwnerProperty)并找出最初创建按钮的ButtonContainer(为什么它可能想要这样做留给读者练习…)。 所有这一切都是可能的,而无需将按钮子类化为狭窄的专业。

这是因为可以为多种类型定义相同的DependencyProperty(使用不同的元数据)

简而言之,当您注册DP时,您将对象(DP)添加到附加到类(所有者)的列表中。 此操作仅“生活”在声明它的类中,并且通常与它无关。