First things first. I’d like to wish everyone a Happy New Year. Here’s hoping that 2008 brings with it happiness, excitement, joy, and wonder!
Recently I came across a blog post that discussed the use of Custom Type Descriptors to dynamically add properties to an object. We currently use this technique in our application, however there is a lot of hocus pocus going on behind the scenes that makes working with that particular piece of code precarious.
I was curious if it would be possible to dynamically declare dependency properties and bind to them using the WPF Binding system. The short answer is yes. The long answer is HELL YES! Believe me using dependency properties to dynamically add properties to your objects is orders of magnitude easier than using custom type descriptors. Something tells me that DPs are just an abstraction of custom type descriptors. Does that make me lazy? Probably. Then again, the less code I have to write to accomplish a task, the less likely I am to introduce bugs, and the quicker I can get to the next task. And as we all know, "programming is fun, but shipping is our job." Besides, you want to trust me on this one…programming Custom Type Descriptors is not fun.
Of course you, my dear readers, are probably wondering, "Why would I want to dynamically register dependency properties?" Isn’t the whole point of a dependency property to allow you to bind to it at design time? Well not only does Mabsterama give a great scenario with the role provider, but there is a well known data modeling pattern known as Entity Attribute Value. I just ran into a post in the forums (which are finally working properly again) where the poster appears to be in need of a similar solution. This encouraged me to finish this post.
My solution relies on a simple class that I call the DependencyPropertyRegistry. The DependencyPropertyRegistry is responsible for dynamically registering dependency properties against a DependencyObject descendant and keeping track of the properties so they can be manipulated. The second part of the solution is a class that wants to dynamically expose properties for binding. The final piece of the puzzle is a control that knows how to properly configure the bindings and display them.
This is easiest explained through code, but I have to do some scrubbing before I can share it with you guys. I promise it will be worth the wait.