Giffyguy
Giffyguy

Reputation: 21302

How do You Create a Read-Only Dependency Property?

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!

Upvotes: 79

Views: 33483

Answers (2)

Konstantin S.
Konstantin S.

Reputation: 1505

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
{
}

Upvotes: 2

Kenan E. K.
Kenan E. K.

Reputation: 14111

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.

Upvotes: 163

Related Questions