In the previous article, titled Dependency Properties, we explored how to create dependency properties for our class. In this article, we are going to explore how to create dependency properties that can only be updated in the defining class itself. As a result, these properties are read-only.
The example for this article can be found in the https://github.com/atzimler/WpfWednesday repository under the Z07_ReadOnlyDependencyProperties directory.
The AddCalculation class has three properties, A, B and Result. A and B properties are read-write properties and changing any of them will update the Result property with the sum of the two numbers. To be able to implement DependencyProperties, the class needs to be derived directly or indirectly from the DependencyObject class.
How read-only dependency properties work
Read-only dependency properties are like the normal dependency properties, except that during the registration instead of a DependencyProperty object, a DependencyPropertyKey object is given back. To update the value, you need the DependencyPropertyKey, while to read it you need a DependencyProperty object.
To register the property, we declare a private static member of the class, so that no code outside of the class can access the value from it.
Then, we publish the DependencyProperty part of the DependencyPropertyKey, so that if there is a code trying to bind to the read-only property it will be possible.
Finally, we implement a read-only accessor property, so that code that does not need binding, can access the properties through a convenient API call.
Here are the unit tests from the codebase in case you are only interested in reading how it works:
And one more thing… I promised in the previous article that we are going to review how to attach event handlers to DependencyProperties during their definitions. The second parameter of the PropertyMetadata class’s constructor allows you to do this. This is used for both A and B properties to update the Result property at the same time.