Ask your Dad!

Something that puzzles me every time I read articles about WPF DependencyObjects, is the fact that they don’t mention how property value inheritance is implemented. Inheritance is used all over the place so property values such as fonts trickle down from parents to their children. While looking at the code in Reflector, I finally twigged how this happens.

Take a simple test type of object,

class TestType : DependencyObject
    private static readonly DependencyProperty s_Property =
        DependencyProperty.Register(“Property”, typeof(string), typeof(TestType),
        new FrameworkPropertyMetadata(“boo”, FrameworkPropertyMetadataOptions.Inherits));

    public string Property
            return (string)GetValue(s_Property);
            SetValue(s_Property, value);

Notice the FrameworkPropertyMetadataOptions, as that turns out to be important. Let’s make two instances, which we’ll assume represent a parent and a child.

var parent = new TestType();
var child = new TestType();

Of course, currently the two instances are unrelated, so the parent value isn’t inherited even though the value isn’t set on the child.

parent.Property = “hello”;
Console.WriteLine(child.Property); // “boo”

Once we call one of the internal functions to relate the two objects (using Reflection), the inheritance starts happening.

MethodInfo method =
    .GetMethod(“SynchronizeInheritanceParent”, BindingFlags.Instance | BindingFlags.NonPublic);
method.Invoke(child, new object[] { parent });
Console.WriteLine(child.Property);   // “hello”

If you use Reflector, you can see that these internal functions are used in the WPF to set up the relevant relationships to get the values inheriting properly.

This entry was posted in Computers and Internet. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s