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

And*_*ech 4 c# wpf dependency-properties

这是我注册的方式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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

DependencyProperty.Register方法的第三个参数要求您指定依赖属性所在的Control的类型(在这种情况下,我的用户控件被调用NewOnlineUserNotifier).

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

Mar*_*ris 7

您调用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);
    }

}
Run Code Online (Sandbox Code Playgroud)

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

使用新类如下:

ButtonContainer container1 = new ButtonContainer();

ButtonContainer container2 = new ButtonContainer();
container2.ChildButton = container1.ChildButton;
Run Code Online (Sandbox Code Playgroud)

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

  • 我们不应该使用附加属性,而不是使用具有不同`ownerType`的普通`DependencyProperty`吗? (2认同)