How to create a read-only dependency property?

How do you create a read-only dependency property? What are the best methods for doing this?

In particular, what strikes me more is that implementations

DependencyObject.GetValue() 

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

System.Windows.DependencyProperty.RegisterReadOnly returns a D object of ependencyPropertyKey , not a DependencyProperty . So, how should you access the read-only dependency property if you cannot make any GetValue calls? Or should you somehow convert DependencyPropertyKey to a plain old DependencyProperty object?

Advice and / or code will be REALLY appreciated!

+51
wpf dependency-properties
Jul 13 '09 at 23:08
source share
1 answer

This is easy, actually (via RegisterReadOnly ):

 public class OwnerClass : DependencyObject // or DependencyObject inheritor { private static readonly DependencyPropertyKey ReadOnlyPropPropertyKey = DependencyProperty.RegisterReadOnly("ReadOnlyProp", typeof(int), typeof(OwnerClass), new FrameworkPropertyMetadata((int)0, 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 setting the value in private / protected / internal code. Thanks to the ReadOnlyProp secure network device, this is transparent to you.

+110
Jul 13 '09 at 23:11
source share
— -



All Articles