What use is a DependencyProperty whose ownerType is not a DependencyObject?
Asked Answered
B

1

7

I've just started playing with DependencyProperties in WPF and I was wanting to check a couple of thoughts while I get to grips with them.

Given the following (and ignoring 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 find that dp2 throws a TypeInitializationException with the message "'MyTestClass' type must derive from DependencyObject" which I expected, but dp1 is accepted quite happily.

Now, I understand why dp2 raises an exception as I'm trying to register property metadata on a type that isn't a DependencyObject and this is fine. I've looked under the covers and can see the code path that both dp1 and dp2 follow so I understand from a code perspective why dp1 doesn't raise the exception but conceptually I would have expected both dp1 and dp2 to raise the same exception.

My question is what use is there in creating a DependencyProperty like dp1 whose ownerType is not a DependencyObject as I cannot see how it can be used without the GetValue/SetValue methods on a DependencyObject.

Berthold answered 25/2, 2011 at 9:48 Comment(0)
C
3

Edit
The reason for the first Register-Signature ist to register a DependencyProperty that has no default-value that could be restored by the Clear-method and also has no registered value change callback.

Because there is no default-value, there will be no check if the default-value is valid and therefore your exception will not be throwed. However is no use of such a registration. You will have no benefit of it and the fact that it does not throw an exception does not mean that it is good for something - it only not is wrong.

Centrifugate answered 25/2, 2011 at 9:57 Comment(3)
Hi, thanks for your reply. I understand why ownerType can be set to any object and the check is performed at runtime. However, my question was really, why does the following NOT throw a runtime exception, and therefore what use is there in creating a DependencyProperty in this way: DependencyProperty.Register("MyProp", typeof(String), typeof(MyTestClass));Berthold
@Matt__E_: Sorry, I would had read the question more exactly. I have changed my answer. BTW +1 for the question.Centrifugate
Hi HCL. Many thanks for taking the time to read my comment and for replying again. I very much appreciate it. I could think of no useful purpose for registering dp1 in that way but as it didn't throw an exception I thought it must have a purpose that I was unaware of. Thanks for confirming that it does nothing useful.Berthold

© 2022 - 2024 — McMap. All rights reserved.