为什么是依赖属性? [英] Why dependency properties?

查看:25
本文介绍了为什么是依赖属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么微软要走依赖属性和依赖对象的路线,而不是使用反射和属性?

Why did Microsoft go the route of making dependency properties and dependency objects instead of using reflection and maybe attributes?

推荐答案

这有助于我理解推理:

主要区别在于,普通 .NET 属性的值是直接读取类中的私有成员,而 DependencyProperty 的值是 在调用从 DependencyObject 继承的 GetValue() 方法时动态解析.

The main difference is, that the value of a normal .NET property is read directly from a private member in your class, whereas the value of a DependencyProperty is resolved dynamically when calling the GetValue() method that is inherited from DependencyObject.

当您设置依赖项属性的值时,它不会存储在对象的字段中,而是存储在基类 DependencyObject 提供的键和值字典中.条目的键是属性的名称,值是您要设置的值.

When you set a value of a dependency property it is not stored in a field of your object, but in a dictionary of keys and values provided by the base class DependencyObject. The key of an entry is the name of the property and the value is the value you want to set.

依赖属性的优点如下:

减少内存占用

当您认为 UI 控件的 90% 以上的属性通常保持其初始值时,为每个属性存储一个字段是一种巨大的浪费.依赖属性通过仅在实例中存储修改的属性来解决这些问题.默认值在依赖属性中存储一次.

It's a huge dissipation to store a field for each property when you think that over 90% of the properties of a UI control typically stay at its initial values. Dependency properties solve these problems by only store modified properties in the instance. The default values are stored once within the dependency property.

价值继承

当您访问依赖项属性时,将使用值解析策略来解析该值.如果没有设置本地值,则依赖属性会向上导航逻辑树,直到找到一个值.当您在根元素上设置 FontSize 时,它​​适用于下面的所有文本块,除非您覆盖该值.

When you access a dependency property the value is resolved by using a value resolution strategy. If no local value is set, the dependency property navigates up the logical tree until it finds a value. When you set the FontSize on the root element it applies to all textblocks below except you override the value.

更改通知

依赖属性具有内置的更改通知机制.通过在属性元数据中注册回调,您会在属性值更改时收到通知.这也被数据绑定使用.

Dependency properties have a built-in change notification mechanism. By registering a callback in the property metadata you get notified, when the value of the property has been changed. This is also used by the databinding.

来自:WPF 教程.

这篇关于为什么是依赖属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆