WPF Tips n' Tricks – Another way to declare read-only dependency properties

Sorry for the hiatus this week-end, I spent a lovely time out of London, disconnected from the online world. Back online (in the train, with WIFI, fantastic, check it out).

Read-only dependency properties (attached or not) are declared by a call to RegisterReadOnly, which returns a DependencyPropertyKey type, which you have to use when setting values. From that object you get a reference to the DependencyPropert object that is used to read values. Let's look at a typical dependency property registration.

public class Div : Control

{

private static DependencyProperty LeftProperty;

private static DependencyPropertyKey LeftPropertyKey;

static Div()

{

Div.LeftPropertyKey = DependencyProperty.RegisterReadOnly(

"Left",

typeof(double),

typeof(Div),

new FrameworkPropertyMetadata(0d));

Div.LeftProperty = Div.LeftPropertyKey.DependencyProperty;

}

Traditionally, you would then define a property with only a getter. But one of the not so known new features of C# 2.0 is the ability to declare different access modifiers for the getter and the setter of a property. We'll use it to our advantage to declare a property getter but have a private setter using the Key, keeping our object model clean and nifty.

public double Left

{

get { return (double)GetValue(Div.LeftProperty); }

private set { SetValue(Div.LeftPropertyKey, value); }

}

And voila, a nice and clean way to set your read-only properties without calls to SetValue all over the place.

[Edit: Added the private as I forgot it. Thanks for correcting me! ]

Ads

Comment