#159 – Creating a Read-Only Dependency Property

Creating a custom dependency property that is read-only is slightly different from creating a standard dependency property.

  • Use DependencyProperty.RegisterReadOnly, rather than Register
  • Create an internal static copy of a DependencyPropertyKey in addition to a public static DependencyProperty
  • Make the CLR property wrapper read-only

For example, assume that we want to add a read-only IQ property to our Person class.

We register the property as read-only and retrieve a DependencyPropertyKey.

        internal static readonly DependencyPropertyKey IQPropertyKey =
            DependencyProperty.RegisterReadOnly("IQ", typeof(int), typeof(Person), new PropertyMetadata(100));

Although the key is private, we make the property public.

        public static readonly DependencyProperty IQProperty =

We can still set the value internally, by using the key.

public Person(string first, string last, int iq)
    FirstName = first;
    LastName = last;
    SetValue(IQPropertyKey, 100);

Finally, we provide a CLR property wrapper.

        public int IQ
            get { return (int)GetValue(IQProperty); }

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: