#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 =
            IQPropertyKey.DependencyProperty;

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); }
        }
Advertisement

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

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: