Question

I tried this out just to see what will happen and it did work but I have no idea why so. Can somebody explain me what is happening in the background of DependencyProperties?

I have a class which declares a DependencyProperty but then in another class I target that DependencyProperty by using GetValue and SetValue.

Here is an example:

public class DependencyProperties : DependencyObject
{
    public Size EstimatedSize
    {
        get { return (Size)GetValue(EstimatedSizeProperty); }
        set { SetValue(EstimatedSizeProperty, value); }
    }

    public static readonly DependencyProperty EstimatedSizeProperty =
        DependencyProperty.Register("EstimatedSize", typeof(Size), typeof(DependencyProperties), null);
}

public class MyControl: ContentControl
{
    public Size CalculatedSize
    {
        get { return (Size)GetValue(DependencyProperties.EstimatedSizeProperty); }
        set { SetValue(DependencyProperties.EstimatedSizeProperty, value); }
    }

    protected override OnApplyTemplate()
    {
      // This works but why? How is it possible to do this? What is happening under the hood?
      this.CalculatedSize = new Size(123, 123);
    }
}

Why is it possible to do this? What is happening in the background of this example? The MyControl class didnt register the DP but it can use it. Can somebody tell me what is happening under the hood?

Was it helpful?

Solution

I googled the image that I'd like to show you. See the link below, and the concept of DP is well documented.

http://www.abhisheksur.com/2011/07/internals-of-dependency-property-in-wpf.html

And, let's go to the bottom-line directly, when you invite and use MyControl in your app, contained DP is automatically registered. This is why DP is use static prefix. For the reason of static readonly in DP declaration, kindly read https://stackoverflow.com/a/5610015/361100 link (Priyank's quoted answer).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top