wpf Read-only dependency properties


When to use

A read-only dependency property is similar to a normal dependency property, but it is structured to not allow having its value set from outside the control. This works well if you have a property that is purely informational for consumers, e.g. IsMouseOver or IsKeyboardFocusWithin.

How to define

Just like standard dependency properties, a read-only dependency property must be defined on a class that derives from DependencyObject.

public class MyControl : Control
    private static readonly DependencyPropertyKey MyPropertyPropertyKey = 
        DependencyProperty.RegisterReadOnly("MyProperty", typeof(int), typeof(MyControl),
            new FrameworkPropertyMetadata(0));

    public static readonly DependencyProperty MyPropertyProperty = MyPropertyPropertyKey.DependencyProperty;

    public int MyProperty
        get { return (int)GetValue(MyPropertyProperty); }
        private set { SetValue(MyPropertyPropertyKey, value); }

The same conventions that apply to regular dependency properties also apply here, but with two key differences:

  1. The DependencyProperty is sourced from a private DependencyPropertyKey.
  2. The CLR property setter is protected or private instead of public.

Note that the setter passes MyPropertyPropertyKey and not MyPropertyProperty to the SetValue method. Because the property was defined read-only, any attempt to use SetValue on the property must be used with overload that receives DependencyPropertyKey; otherwise, an InvalidOperationException will be thrown.