加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

wpf – 依赖属性如何告诉对象应用于?

发布时间:2020-12-13 20:45:55 所属栏目:百科 来源:网络整理
导读:(我对这个概念完全陌生,所以我可能会问非常基本的问题.) 使用以下代码注册依赖项属性: public static DependencyProperty Register(string name,Type propertyType,Type ownerType,PropertyMetadata typeMetadata); 从逻辑上讲,它只是将属性名称与所有者类
(我对这个概念完全陌生,所以我可能会问非常基本的问题.)

使用以下代码注册依赖项属性:

public static DependencyProperty Register(string name,Type propertyType,Type ownerType,PropertyMetadata typeMetadata);

从逻辑上讲,它只是将属性名称与所有者类型相关联.

因此,如果我有所有者类型的多个实例,并且每个实例都将DP设置为不同的值.

如何存储这些值?

更新1 – 2013年10月30日上午10:04

我从这里读到了附属物:http://wpftutorial.net/DependencyProperties.html

Attached Properties

Attached properties are a special kind of DependencyProperties. They
allow you to attach a value to an object that does not know anything
about this value.

A good example for this concept are layout panels. Each layout panel
needs different data to align its child elements. The Canvas needs Top
and Left,The DockPanel needs Dock,etc. Since you can write your own
layout panel,the list is infinite. So you see,it’s not possible to
have all those properties on all WPF controls.

The solution are attached properties. They are defined by the control
that needs the data from another control in a specific context. For
example an element that is aligned by a parent layout panel.

所以在以下代码片段中:

<Canvas>
    <Button Canvas.Top="20" Canvas.Left="20" Content="Click me!"/>
    <Button Canvas.Top="40" Canvas.Left="20" Content="Click me!"/>
</Canvas>

显然我们不能给出所有对齐属性,例如Top,Left to Button.因此,Canvas定义了这些属性,并将它们“附加”到Button控件上.

当Canvas.Top被指定为XAML中Button的“属性”时,它将调用Canvas类型中定义的SetTop()方法. Button作为元素参数传入.
我认为这就是Canvas如何知道哪个Button使用哪个Top值.

public static void SetTop(UIElement element,double length);

但我不明白为什么附属财产必须是依赖财产?它们之间的联系是什么?

谢谢!

通常在我们定义DependencyProperty时,我们还定义了一个CLR’包装器’,它使我们能够在代码中使用DependencyProperty:
public static readonly DependencyProperty ItemsProperty = DependencyProperty.Register(
    "Items",typeof(ObservableCollection<string>),typeof(MainWindow),new UIPropertyMetadata(new ObservableCollection<string>()));

public ObservableCollection<string> Items
{
    get { return (ObservableCollection<string>)GetValue(ItemsProperty); }
    set { SetValue(ItemsProperty,value); }
}

在这里,您可以看到@Clemens所讨论的GetValue和SetValue方法.我们可以在Window和/或UserControl中访问这些方法,因为它们都扩展了DependencyObject类.您还可以看到这里的Items属性不是静态的……它只是DependencyProperty的静态定义.

更新>>>

要问为什么附属财产必须是DependencyProperty并没有多大意义?因为在.NET中,它们只是……它们就是这样设计的.一个更好的问题可能是,附属财产从DependencyProperty获得了什么好处?

答案就像被问到属性从DependencyProperty获得什么好处一样?主要的好处是这些属性可用于绑定,样式,动画和资源等.更多详细信息可以从MSDN上的两个非常重要的页面(已经链接到评论中)找到,适用于任何WPF开发人员:

Dependency Properties Overview

Attached Properties Overview

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读