8

I'm hoping someone can explain some unexpected behaviour I have come across whilst continuing my exploration of DependencyObjects and DependencyProperties.

Given the following simple class:

    class SomeClass : DependencyObject {
    }

I can happily write code such as:

public static void Test() {
  SomeClass a = new SomeClass();
  Console.WriteLine(a.GetValue(EllipseGeometry.RadiusXProperty));
  a.SetValue(EllipseGeometry.RadiusXProperty, 3.24 );
  Console.WriteLine(a.GetValue(EllipseGeometry.RadiusXProperty));
}

which gives the following output:

0
3.24

There is nothing in my class that has any relation to the EllipseGeometry class, and I have not added my class as an owner of the EllipseGeometry.RadiusXProperty property or used RegisterAttached() so why does this work? It seems I can quite happily add any DP to my DO without the Framework raising an error.

Does anyone else find this strange behaviour? I would have expected some form of exception along the lines of "You have not registered this property with this object"... I would appreciate any guidence as to whether there is any particular use for adding DPs to DOs in this way, as I cannot see the purpose of allowing this behaviour.

Many thanks, Matt

Matt__E_
  • 277
  • 2
  • 9
  • I'm guessing `SomeClass` is meant to be `TestClass` (or vice versa)? – Steven Jeuris Mar 01 '11 at 00:55
  • Is EllipseGeometry.RadiusXProperty an attached property? – Double Down Mar 01 '11 at 00:57
  • Hi Steven, you guess correctly and I had a copy and paste error. I've renamed TestClass to SomeClass. It's late, what more can I say. Thanks for taking the time to answer – Matt__E_ Mar 01 '11 at 01:01
  • Hi DoubleDown, the EllipseGeometry.RadiusXProperty is just a random DependencyProperty I chose to illustrate my question so there is nothing particularly special about it as far as I know. There is nothing more to SomeClass than what I posted above - it seems I can use any DP in this way on any DO which just seems, well, odd. Thanks for replying – Matt__E_ Mar 01 '11 at 01:07
  • There's no harm in assigning a DP to a DO that doesn't actually have that DP, so why waste time with unnecessary error checking? – Gabe Mar 01 '11 at 13:48

1 Answers1

1

This behavior allows you to use attached properties. Without this, how can you use Grid.Row on a TextBox for instance.

thewpfguy
  • 794
  • 6
  • 15