Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 971
Giffyguy Avatar asked Jul 13 '09 23:07

Giffyguy


People also ask

How do you create a dependency property?

To create new dependency property we need to follow the below procedure, Declare and register dependency property. For registered property set value using SetValue method and get value using GetValue method. Write a method to handle change done on dependency property.

How do you define dependency property?

A dependency property is a specific type of property where the value is followed by a keen property system which is also a part of the Windows Runtime App. A class which defines a dependency property must be inherited from the DependencyObject class.

Why is dependency property static readonly?

Because it makes it obvious, that the value of this property cannot be changed after initialization.


1 Answers

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.

like image 117
Kenan E. K. Avatar answered Sep 22 '22 08:09

Kenan E. K.