#147 – Use SetCurrentValue When You Want to Set A Dependency Property Value from Within a Control
December 6, 2010 3 Comments
As a control author, you might want to set the value of one of your own dependency properties. For example, a numeric up/down control might want to change its Value property in response to clicking on the arrows.
The problem with setting the dependency property directly is that you’ve set a local value, which will take precedence over all other possible sources, like data binding. If you set a local value, you’ll destroy any data binding that the application has set up.
The solution is to use the DependencyObject.SetCurrentValue method to set the current value from within the control. This is similar to coercion, in that the effective value is changed without affecting the property’s value source.
A control should always use SetCurrentValue to set the value of its own dependency properties, with the exception of the CLR property setter, which should use SetValue.
See also Vincent Sibal’s blog.
You can enable what would otherwise be a common language runtime CLR property to support styling data binding inheritance animations and default values by implementing it as a dependency property. The identifier field is also provided by the method call as the return value.
Just want to clarify one thing: according to Post #133
WPF determines the final value for a dependency property as follows:
Determine the base value, using the precedence rules listed below
Evaluate expressions
Apply animations
Coerce value (implementing class might coerce to valid value)
Validate (implementing class may throw exception if value is invalid)
Local value is evaluated when the base value is determined. Data binding is one type of evaluation expressions. My understanding is the base value should be retrieved first before applying evaluation expressions, animation and coercion. So I feel the evaluate expressions should have precedence over the local value. But this seems conflicting with above statement: If you set a local value, you’ll destroy any data binding that the application has set up.
Sadly what you say make sense to me. I’m losing bindings, even if using SetCurrentValue.
Any other workaround to set a baseclass dependency property’s default value from within the control?