#114 – How Dependency Properties Are Implemented

Dependency properties in WPF can be used by a client just like regular CLR properties, but they are implemented differently in the defining class.  The added complexity serves to support features like data binding, property inheritance and change notification.

Classes that want to implement a dependency property start by by inherting from DependencyObject, which provides the support for reading and writing dependency property values.

The class then declares a static variable of type DependencyProperty for the new property.  A static instance is created using the DependencyProperty.Register function.  This instance does not store property values, but stores metadata about the property.

        public static readonly DependencyProperty AgeProperty =
            DependencyProperty.Register("Age", typeof(int), typeof(Person));

Dependency property values are managed by the GetValue and SetValue methods inherited from the DependencyObject class.

        public int Age
        {
            get { return (int)GetValue(AgeProperty); }
            set { SetValue(AgeProperty, value); }
        }
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #114 – How Dependency Properties Are Implemented

  1. Pingback: #153 – You Can Set the Value of any Dependency Property for any Dependency Object « 2,000 Things You Should Know About WPF

Leave a Reply

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

WordPress.com Logo

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

Facebook photo

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

Connecting to %s

%d bloggers like this: