【问题标题】:WPF Dependency Properties: Why do I need to specify an Owner Type?WPF 依赖属性:为什么需要指定所有者类型?
【发布时间】:2009-05-15 13:46:58
【问题描述】:

这就是我注册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)。

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

【问题讨论】:

    标签: c# wpf dependency-properties


    【解决方案1】:

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

    当您创建包含其他控件的自定义控件时,这可能很有用。以前使用 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(为什么要这样做,留给读者练习......)。所有这些都是可能的,无需将按钮子类化为一个狭窄的专业。

    【讨论】:

    • 我们不应该使用附加属性而不是普通的DependencyProperty 和不同的ownerType吗?
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-05-24
        • 2018-12-10
        • 2020-09-11
        • 2018-11-21
        • 1970-01-01
        • 2010-12-15
        • 2012-11-08
        相关资源
        最近更新 更多