EditCategory
Fundamentals
EditQuestion
How do I create a read-only DependencyProperty?
EditAnswer
Creating a read-only property is very much similar to creating a regular DependencyProperty.
Refer to the related links for details on creating dependency properties.
When declaring a read-only property, the return value of the DependencyProperty.RegisterReadOnly() method is a DependencyPropertyKey instead of the DependencyProperty returned by the DependencyProperty.Register() function.
The DependencyPropertyKey should be stored in a private static readonly or protected static readonly field (as opposed to regular dependency properties, which should be public static readonly fields). This is because one could modify the value of the read-only property by accessing its DependencyPropertyKey.
Instead, you should declare another DependencyProperty field (public static readonly) and assign to it the DependencyPropertyKey.DependencyProperty property.
This property contains the read-only DependencyProperty which can then be used by class users.
Inside your class, you can then use the DependencyPropertyKey when changes are needed on the read-only property.
Example:
public CustomClass1 : DependencyObject
{
#region 'ReadonlyProp' dependency property
private static readonly DependencyPropertyKey ReadonlyPropKey = DependencyProperty.RegisterReadOnly(
"ReadonlyProp", typeof(int), typeof(CustomClass1), new PropertyMetadata());
public static readonly DependencyProperty ReadonlyPropProperty = ReadonlyPropKey.DependencyProperty;
public int ReadonlyProp{
get { return (int)GetValue(ReadonlyPropProperty); }
private set { SetValue(ReadonlyPropKey, value); }
}
#endregion
}
EditRelated Links
How to declare a dependency property