How do You Create a Read-Only Dependency Property?
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.
Giffyguy
I enjoy writing hardcore OO data-structures in native C++.
Updated on April 27, 2020Comments
-
Giffyguy about 4 years
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 aDependencyProperty
. 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 theDependencyPropertyKey
into a plain oldDependencyProperty
object?Advice and/or code would be GREATLY appreciated!
-
Rahul Sonone about 6 yearsCan you please one real time example or requirement where we use, this ReadOnly dependency property?
-
Josh Noe about 6 years@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.
-
Flynn1179 about 5 yearsActualWidth/ActualHeight of any control are one good example.
-
StayOnTarget about 4 yearsYou might want to update
"ReadOnlyProp"
tonameof(ReadOnlyProp)
because a lot of people probably copy/paste this and they might as well use the current & improved syntax. -
Kenan E. K. about 4 yearsNo 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#.