为什么一个控件(按钮)的依赖属性的更改不会影响它的所有实例?
这可能是一个愚蠢的问题。
- 依赖属性本质上是静态的。
- Button(基本上是一个公共类)有很多依赖属性。
如果我在窗口中使用两个按钮,这意味着同一类的不同实例......但静态属性应该只有一个。如果我更改一个按钮更改的依赖属性,其他按钮也应该更改,对吗?
谢谢 安尼什
This might be a stupid question.
- Dependency properties are static in nature.
- Button (which is basically a public class) has somany dependnency properties.
If I use two button in my window, that means different instances of same class...but the static property should be only one. If I change Dependency property of one button change, other should also be changed, right ?
Thanks
Anish
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
DependencyProperty 与常规属性不同。它是一个属性定义,依赖于另一个属性来获取其值。它并不意味着包含一个值,而是包含一个指向另一个值的指针。
如果执行类似
的操作,则将 Text DepdencyProperty 的值指向表示“Test”的字符串值。如果执行
,则将值指向 TextBlock 的 DataContext(通常是一个类)上名为UserName
。我实际上在这里写了一些关于 DependencyProperties 与如果您有兴趣,常规属性
A DependencyProperty is not the same as a regular property. It is a property definition that depends on another property to get it's value. It's not meant to contain a value, but instead contains a pointer to another value.
If you do something like
<TextBlock Text="Test" />
, you are pointing the value of the Text DepdencyProperty to a string value which says "Test". If you do<TextBlock Text="{Binding UserName}" />
, you are pointing the value to a property on the TextBlock's DataContext (usually a class) calledUserName
.I actually wrote something here about how DependencyProperties differ from regular properties if you're interested
归结为这个概念,这可能会帮助您理解它:
依赖属性就像字典,如果使用
SetValue
,则会创建带有控件键的新条目以及您设置的值,或者值被覆盖。稍后可以使用GetValue
查找该值。只有这个字典是静态的,CLR-Wrappers 不是,否则对象实例无法添加为键。
拥有依赖属性的要点是实际上在控件的每个实例上都没有那么多字段(正如您提到的按钮有很多属性),这样可以分层查找值,最终返回到默认值在字段定义上定义的值。
当然,另请参阅MSDN 上的文章以获得更正确和更详细的信息对问题的深度看法。
Boiled down to the concept this might help you understand it:
Dependency properties are like dictionaries, if
SetValue
is used a new entry with the key of the control and the value you set is created or the value is overwritten. This value can be looked up withGetValue
later.Only this dictionary is static, the CLR-Wrappers are not, otherwise the object instances could not be added as key.
The point of having dependency properties is to not actually have that many fields on ever instance of a control (as you mentioned a Button has quite many properties), that way values can be looked up hierarchically, ultimately going back to a default value defined on the field definition.
Also see of course the articles on MSDN for a more correct and in-depth view on the issue.