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

2024-06-25

这就是我注册的方式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方法要求您指定依赖属性所在的控件的类型(在本例中,我的用户控件称为NewOnlineUserNotifier).

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


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

当您创建包含其他控件的自定义控件时,这可能很有用。以前使用 WinForms 时,如果您有一些仅对该容器有用但在语义上属于子容器的额外信息,那么您能做的最好的事情就是将该信息放置在保留所有“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 最初创建了该按钮(为什么它可能想要这样做,留给读者作为练习......)。所有这一切都是可能的,而不需要将按钮细分为一个狭窄的专业。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

WPF 依赖项属性:为什么需要指定所有者类型? 的相关文章

随机推荐