views:

450

answers:

1

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!

+6  A: 

It's easy, actually:

    private static readonly DependencyPropertyKey ReadOnlyPropPropertyKey
        = DependencyProperty.RegisterReadOnly("ReadOnlyProp", typeof(int), typeof(OwnerClass),
            new FrameworkPropertyMetadata((int)0,
                FrameworkPropertyMetadataOptions.None,
                new PropertyChangedCallback(OnReadOnlyPropChanged)));

    public static readonly DependencyProperty ReadOnlyPropProperty
        = ReadOnlyPropPropertyKey.DependencyProperty;

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

    private static void OnReadOnlyPropChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        ((OwnerClass)d).OnReadOnlyPropChanged(e);
    }

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.

kek444
That makes perfect sense! I had no idea the DependencyProperty was a member of the DependencyPropertyKey. Thanks a ton!
Giffyguy
Yeah, I was baffled the first time I tried to wrap my head around it too. You're welcome!
kek444