#147 – Use SetCurrentValue When You Want to Set A Dependency Property Value from Within a Control

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.

About these ads

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #147 – Use SetCurrentValue When You Want to Set A Dependency Property Value from Within a Control

  1. Monex says:

    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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 349 other followers

%d bloggers like this: