附加属性
我对 WPF 附加属性有点困惑。当您使用附加属性时,附加属性只能由定义它的类读取和使用,正确吗?例如,如果我想使用某些附加属性作为按钮上的悬停颜色,我可以从按钮的模板中获取附加属性值吗?我是否能够从按钮访问附加属性来设置悬停颜色?
I am a little confused about WPF attached properties. When you use an attached property that attached property can only be read and used by the class that defines it correct? For example if I wanted to use some attached property as a hover color on a button, can I get the attached property value from the button's template, and will I be able access the attached property from the button to set the hoover color?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用示例添加 HB 的答案:
是的,你当然可以。假设您在名为 SomeClass 的类中定义了一个名为
HoverBrush
的附加属性,您可以在实例上设置该值并在模板中绑定到它。有问题的附加属性定义如下
Adding to the answer from H.B. using an example:
Yes, you sure can. Say that you have an Attached Property called
HoverBrush
defined in a class called SomeClass, you can set the value on the instance and bind to it in the templateThe attached property in question is defined like this
您是否已阅读概述?如果没有,那就去做吧。
附加属性,例如依赖属性,只需注册另一个可在控件属性字典中使用的键即可。您可以在任何地方设置值,也可以在任何地方检索它们,它们不受类型限制。这意味着您可能只希望在按钮上设置它,但也可以在文本框上设置它。
每个控件都有自己的属性键和值的字典,附加属性允许您使用新键将值写入这些字典。由于这些字典是独立的,因此它们可以为通过静态字段属性声明设置和访问的同一属性拥有单独的值。
当附加这些属性时,您必须通过 GetValue 获取值(因为类本身无法提供 CLR 包装器)。
Have you read the overview? If not, do it.
Attached properties, like dependency properties, just register another key that can be used in the properties dictionary of controls. You can set values anywhere and you can retrieve them anywhere, they are not restricted by type. This means that you may only want it to be set on Buttons but it can be set on TextBoxes too.
Every control has its own dictionary of property keys and values, an attached property allows you to write a value to those dictionaries using a new key. As those dictionaries are independent they can have separate values for the same property which is set and accessed via the static field property declaration.
As those properties are attached you will have to get the values via the
GetValue
(as the classes cannot provide a CLR-wrapper themselves).