How to create DependencyProperty in WPF in 5 minutes

Have you tried to create a DependencyProperty on one of your UserControl or DependencyObject in WPF only to find that your extra bits of code don’t get run when you raise PropertyChanged? This will take you through everything you need to do in order to fire custom code on the PropertyChagned event.

First, create your class and inherit from DependencyObject, or create a new UserControl that inherits DependencyProperty.

Next, create a DependencyProperty using the code snippet propdp and hitting TAB:

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

        // Using a DependencyProperty as the backing store for Age.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty AgeProperty =
            DependencyProperty.Register("Age", typeof(int), typeof(Person), new UIPropertyMetadata(0));

At this point, you’d think that you can modify the Age property’s access modifiers. Not the case.

Instead, you need to create a callback to handle the PropertyChanged event and attach this to the DepedencyProperty. Here’s the completed definition:

        public int Age
        {
            get { return (int)GetValue(AgeProperty); } //do NOT modify anything in here
            set { SetValue(AgeProperty, value); } //...or here
        }

        // Using a DependencyProperty as the backing store for Age.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty AgeProperty =
            DependencyProperty.Register(
            "Age",  //Must be the same name as the property created above
            typeof(int), //Must be the same type as the property created above
            typeof(Person), //Must be the same as the owner class
            new UIPropertyMetadata(
                0,  //default value, must be of the same type as the property
                new PropertyChangedCallback((s, e) =>  //A callback that gets executed when the property changed
                {
                    var source = s as Person;
                    s.DOB_Year = DateTime.Now.Year - s.Age;Â
                })));

Place your code in the callback, and it will get executed when the event is raised and the property has been changed.

Note that this is not thread safe, and you’ll need to use Dispatcher.Invoke to safely set other properties in this callback.

Leave a Comment


9 * = eighteen


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>