How do You Create a Read-Only Dependency Property?

29,802

It's easy, actually (via RegisterReadOnly):

public class OwnerClass : DependencyObject // or DependencyObject inheritor
{
    private static readonly DependencyPropertyKey ReadOnlyPropPropertyKey
        = DependencyProperty.RegisterReadOnly(
            nameof(ReadOnlyProp),
            typeof(int), typeof(OwnerClass),
            new FrameworkPropertyMetadata(default(int),
                FrameworkPropertyMetadataOptions.None));

    public static readonly DependencyProperty ReadOnlyPropProperty
        = ReadOnlyPropPropertyKey.DependencyProperty;

    public int ReadOnlyProp
    {
        get { return (int)GetValue(ReadOnlyPropProperty); }
        protected set { SetValue(ReadOnlyPropPropertyKey, value); }
    }

    //your other code here ...
}

You use the key only when you set the value in private/protected/internal code. Due to the protected ReadOnlyProp setter, this is transparent to you.

Share:
29,802
Giffyguy
Author by

Giffyguy

I enjoy writing hardcore OO data-structures in native C++.

Updated on April 27, 2020

Comments

  • Giffyguy
    Giffyguy about 4 years

    How do you create a read-only dependancy property? What are the best-practices for doing so?

    Specifically, what's stumping me the most is the fact that there's no implementation of

    DependencyObject.GetValue()  
    

    that takes a System.Windows.DependencyPropertyKey as a parameter.

    System.Windows.DependencyProperty.RegisterReadOnly returns a DependencyPropertyKey object rather than a DependencyProperty. So how are you supposed to access your read-only dependency property if you can't make any calls to GetValue? Or are you supposed to somehow convert the DependencyPropertyKey into a plain old DependencyProperty object?

    Advice and/or code would be GREATLY appreciated!

  • Rahul Sonone
    Rahul Sonone about 6 years
    Can you please one real time example or requirement where we use, this ReadOnly dependency property?
  • Josh Noe
    Josh Noe about 6 years
    @RahulSonone anytime you don't want the property to be set from outside the control class. If you don't make it read only, you can set it in XAML etc.
  • Flynn1179
    Flynn1179 about 5 years
    ActualWidth/ActualHeight of any control are one good example.
  • StayOnTarget
    StayOnTarget about 4 years
    You might want to update "ReadOnlyProp" to nameof(ReadOnlyProp) because a lot of people probably copy/paste this and they might as well use the current & improved syntax.
  • Kenan E. K.
    Kenan E. K. about 4 years
    No problem, thanks for the suggestion. To be honest, this is an old answer and I am not "maintaining" updated versions of answers myself. Also, these days I'm much more on javascript than C#.