78

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!

akjoshi
  • 15,374
  • 13
  • 103
  • 121
Giffyguy
  • 20,378
  • 34
  • 97
  • 168

2 Answers2

161

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.

Kenan E. K.
  • 13,955
  • 3
  • 43
  • 48
  • 1
    Can you please one real time example or requirement where we use, this ReadOnly dependency property? – Rahul Sonone Apr 09 '18 at 18:50
  • 2
    @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. – Josh Noe May 09 '18 at 21:39
  • 2
    ActualWidth/ActualHeight of any control are one good example. – Flynn1179 Jun 14 '19 at 12:02
  • 4
    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. – StayOnTarget Apr 08 '20 at 11:56
  • 1
    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#. – Kenan E. K. May 25 '20 at 07:46
1

I want to note that at the current time it is better to use https://github.com/HavenDV/DependencyPropertyGenerator, the code will be extremely simple:

[DependencyProperty<int>("ReadOnlyProperty", IsReadOnly = true)]
public partial class MyControl : UserControl
{
}
Konstantin S.
  • 1,307
  • 14
  • 19