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

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

问题描述

Microsoft为什么不采用制作依赖属性和依赖对象而不是使用反射和属性的方法?

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

推荐答案

帮助我理解了原因:

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

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.

依赖项属性的优点如下:

The advantages of dependency properties are as follows:

减少的内存占用

当您认为每个属性都存储一个字段时,这是很大的浪费通常,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天全站免登陆