Monday, October 23, 2006

DependencyProperty and DependencyObject

I’ll admit, the DependencyObject and DependencyProperty have been a bit difficult for me to grasp. However, it must be a big thing based on the way that Windows Workflow (WF) and Windows Presentation Foundation (WPF) utilize it. So I felt it important to blog about my experiences and discoveries around these classes.
Any class can be defined as a DependencyObject by simply deriving from it. But why would anyone want to do that? First off, we must understand that a DependencyObject is essentially a container for DependencyProperty items. I know, I know, that still doesn’t define why we would want to use them. So, let’s examine why we should use them.

Well, essentially, I had to envision how data binding in WPF works in order to understand why I would want to use this. Let’s pretend that we are creating a Windows Forms application (pre-WPF). Our Windows Forms application will contain a knob control that we’ve created and a media player. Our knob will adjust the volume of the media player. Well, traditionally, we would have to programmatically handle the event of adjusting the knob and when the knob adjusts, we must adjust the volume of the media player.

This is the Ah Ha moment… you see, if our knob control had a DependencyProperty called “VolumeLevel”, we could bind the media player’s volume setting to this property and voila! It’s automatically handled for you. When the value of “VolumeLevel” is altered, the volume setting of the media player will be changed as well. I like to think of a DependencyProperty as sort of a radio station that broadcasts the info to its listeners (i.e. the items that are binding to the property).

In addition to data binding, there are a number of other services you can take advantage of. I want to make sure to give credit where credit is due, so you may find a brief list of those services

No comments: