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 meth开发者_StackOverflow社区ods on a DependencyObject.
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.
精彩评论