Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I access DependencyProperties that are not registered on my DependencyObject?

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

like image 482
Matt__E_ Avatar asked Mar 01 '11 00:03

Matt__E_


People also ask

How do you use dependency property?

Custom Dependency Properties Follow the steps given below to define custom dependency property in C#. Declare and register your dependency property with system call register. Provide the setter and getter for the property. Define an instance handler which will handle any changes that occur to that particular instance.

How does dependency property work internally?

A DependencyProperty maintains a static reference of all the DependencyProperty you register in WPF object hierarchy. It maintains a HashTable named PropertyFromName which it uses internally to get the DependencyProperty object. So in other word, each dependencyProperty object is registered in a global HashTable.

Which is dependency property in this code?

A dependency property is a specific type of property where the value is followed by a keen property system which is also a part of the Windows Runtime App. A class which defines a dependency property must be inherited from the DependencyObject class.


1 Answers

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

like image 57
thewpfguy Avatar answered Oct 05 '22 04:10

thewpfguy