#159 – Creating a Read-Only Dependency Property
December 18, 2010 Leave a comment
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); } }