What's the difference between Dependency Property SetValue() & SetCurrentValue()

南楼画角 提交于 2019-11-26 09:09:02

问题


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.


回答1:


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.




回答2:


Further to the accepted answer:

I found that this post explains SetCurrentValue() quite well. Note how the Dependency Property Value Precedence system will take a local value over a bound value. Which explains the commenters unexpected behaviour.



来源:https://stackoverflow.com/questions/4230698/whats-the-difference-between-dependency-property-setvalue-setcurrentvalue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!