Internal of DependencyProperty (2)
Set the value of DP
In the preceding sections, it shows you how to register and what .NET does for you. If we want to set the value of MyContent, we just need to dot this:
this.TestCtrl1.MyContent = "Button Clicked!";
According to the definition of this property, you can find that it invokes SetValue method internally.
What happens in SetValue…?
It takes three steps to do this, as the following diagram.
[1.1] you should know the DP can only be set by the thread that creates it, how to ensure this is done in VerifyAccess, which calls Dispatcher.VerifyAccess method. The Dispatcher maintains a prioritized queue of work items for a specific thread.
When a Dispatcher is created on a thread, it becomes the only Dispatcher that can be associated with the thread, even if the Dispatcher is shut down. Dispatcher.VerifyAccess checks whether current thread is the thread that creates it.
[1.2] it gets the PropertyMetadata with the help of GetMetadata, which is discussed previously.
[1.3] it is responsible for setting the value. If you have read the WPF unleashed, you may remember the following diagram.
It illustrates the five-step process that WPF runs each dependency property through in order to calculate its final value.
First, let’s take a look at the sequence diagram.
Here is one thing that all the values of the DependencyProperty are stores in _effectiveValues, which is an instance field in DependencyObject. That means before setting the value, it needs to search this field first in order to find the existing value for this property. This step is done by LookupEntry method [1.1], this method returns an EntryIndex, which is the location of the property in the _effectiveValues. _effectiveValues is an array of EffectiveValueEntry, which contains the value of the property and also includes some methods to modify the value. These methods will be discussed later.
[1.2] next step is to validate the value that you’re going to set.
[1.3] since it gets the location in step 1.1, it can use the index to get the EffectiveValueEntry.
[1.4] it creates a new EffectiveValueEntry object, which can be used to store the new value.
[1.5] UpdateEffectiveValue method finishes the five-step process.
After the final value is calculated, the value is stored in the _effectiveValues field.
Get the value of DP
You can retrieve the value through GetValue method.