What is the use of DependencyProperty whose ownerType is not a DependencyObject?

I was just starting to play with DependencyProperties in WPF, and I wanted to test a couple of thoughts while I deal with them.

Given the following (and ignoring the naming convention for now):

class MyTestClass { public static readonly DependencyProperty dp1 = DependencyProperty.Register("MyProp", typeof(String), typeof(MyTestClass)); public static readonly DependencyProperty dp2 = DependencyProperty.Register("MyProp2", typeof(String), typeof(MyTestClass), new PropertyMetadata("Hello")); } 

I found that dp2 throws a TypeInitializationException with the message "Type MyTestClass" must be obtained from DependencyObject ", which I expected, but dp1 is accepted quite happily.

Now I understand why dp2 throws an exception, because I am trying to register property metadata in a type that is not DependencyObject, and this is normal. I looked under the covers and I see the path to the code that executes both dp1 and dp2, so I understand from the point of view of the code why dp1 does not throw an exception, but conceptually I expected that both dp1 and dp2 will raise the same thing an exception.

My question is what needs to be used to create a DependencyProperty, such as dp1, whose ownerType is not a DependencyObject, since I don’t see how it can be used without the GetValue / SetValue methods in DependencyObject.

+6
c # wpf dependency-properties dependencyobject
source share
1 answer

Edit
The reason for the first register-register is to register DependencyProperty , which does not have a default value that can be restored using the Clear method, and also does not have a registered value change callback.

Since there is no default value, there will not be a check to see if the default value is valid and therefore your exception will not be thrown. However, such registration is not needed. You will not get any benefit from this, and the fact that it does not throw an exception does not mean that it is good for something - it’s just not so.

+3
source share

All Articles