Monday, March 9, 2009

How to Create Dependency Properties in Silverlight

You can pretty much cut and paste this snippet in your code and change a few names and values in order to properly register a dependency property for your Silverlight class.

First of all, you need to create public property whose getter and setter call GetValue and SetValue respectively. You then define a public static read only Dependency property. This must have the name given to the public property defined earlier with "Property" appended to it. In this step you want to register this dependency property and specify the name, type, type of object to which it is being registered, and specify the method to call when the property is changed. If you do not need to call a method to do some processing every time the property value changes, the last parameter in the Register method can be set to null. That's about it.

So, in this snippet I am registering a dependency property named HorizontalOffset of type double. I am registering this property on a class I called Stack3DPanel. This class happens to be a custom panel, so whenever I change this property, I want all the elements in my panel to be redrawn, so I'm calling the InvalidateArange method. The body of this method can be whatever you need it to be. Again, if you do not need to do anything when the property is changed, you can set that fourth parameter in the Register call to null.

Here is the code.


        public double HorizontalOffset
get { return (double)GetValue(HorizontalOffsetProperty); }
set { SetValue(HorizontalOffsetProperty, value); }

public static readonly DependencyProperty HorizontalOffsetProperty =
new PropertyMetadata(new PropertyChangedCallback(Stack3DPanel.OnHorizontalOffsetPropertyChanged)));

private static void OnHorizontalOffsetPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
Stack3DPanel pnl = d as Stack3DPanel;
if (pnl != null)