依赖项属性SetValue()和&的区别是什么? SetCurrentValue() [英] What's the difference between Dependency Property SetValue() & SetCurrentValue()

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

问题描述

之所以这样问,是因为@Greg D推荐了我(来自

SetValue()

设置依赖项属性的本地值,该值由其依赖项属性标识符指定.

SetCurrentValue()

设置依赖项属性的值,而不更改其值源.

解决方案

您提供的MSDN链接说得很好:

此方法由组件使用 以编程方式设置值 自己的属性之一而没有 禁用应用程序的声明 财产的使用.这 SetCurrentValue方法更改 财产的有效价值,但 现有触发器,数据绑定和 样式将继续起作用.

假设您正在编写TextBox控件,并且已经公开了人们经常使用的Text属性,如下所示:

<TextBox Text="{Binding SomeProperty}"/>

在控件的代码中,如果调用SetValue,则将使用您提供的任何内容覆盖.但是,如果调用SetCurrentValue,将确保该属性采用给定的值,但不会破坏任何绑定.

据我所知,格雷格的建议是不正确的.您应该始终在CLR包装器属性中使用GetValue/SetValue. SetCurrentValue在需要属性采用给定值但不想覆盖已针对该属性配置的任何绑定,触发器或样式的情况下更有用.

The reason why I am asking this is because I was recommended by @Greg D (from this question) to use SetCurrentValue() instead, but a look at the docs and didn't see whats the difference. Or whats does "without changing its value source" mean?

SetValue()

Sets the local value of a dependency property, specified by its dependency property identifier.

SetCurrentValue()

Sets the value of a dependency property without changing its value source.

解决方案

The MSDN link you provided says it quite well:

This method is used by a component that programmatically sets the value of one of its own properties without disabling an application's declared use of the property. The SetCurrentValue method changes the effective value of the property, but existing triggers, data bindings, and styles will continue to work.

Suppose you're writing the TextBox control and you've exposed a Text property that people often use as follows:

<TextBox Text="{Binding SomeProperty}"/>

In your control's code, if you call SetValue you will overwrite the binding with whatever you provide. If you call SetCurrentValue, however, will ensure that the property takes on the given value, but won't destroy any bindings.

To the best of my knowledge, Greg's advice is incorrect. You should always use GetValue/SetValue from your CLR wrapper property. SetCurrentValue is more useful in scenarios where you need a property to take on a given value but don't want to overwrite any bindings, triggers, or styles that have been configured against your property.

这篇关于依赖项属性SetValue()和&amp;的区别是什么? SetCurrentValue()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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