Jan 27

Creating attached properties

Posted in Silverlight      Comments Off on Creating attached properties

Now that you understand what attached properties are, we’re in the position to look at what is needed for creating attached properties. Since we’re building custom code, we do really need to rely in the RegisterAttached method (of the DependencyProperty class). Creating a new attached properties means doing the following:

  1. adding a static DependencyProperty field to the class;
  2. using the RegisterAttached method for creating the field which is used as a store for the dependency property;
  3. add a couple of static methods named GetXXX/SetXXX (where XXX is the name of the property) used as shortcuts for getting and setting the attached property from code.

Let’s suppose that we were creating a new look-a-like Canvas class. Here’s the code you’re expected to add to your class for the Left property:

public class MyCanvas: Panel {
    public static DependencyProperty LeftProperty;
    static MyCanvas() {
        LeftProperty = DependencyProperty.RegisterAttached(
            typeof (Double),
            typeof (MyCanvas),
            new PropertyMetadata(null));
    public static Double GetLeft(UIElement element) {
        return (Double) element.GetValue(LeftProperty);
    public static void SetLeft(
UIElement element, Double value) { element.SetValue(LeftProperty,value); } }

As you can see, we need to start by registering the attached property through the RegisterAttached method. The method expects four parameters: the name of the property, the type of the property, the type of the “owner” of this property (generally, this will be the class that exposes the attached prop) and the associated metadata (notice that if you’re not interesting in setting a default value or in associating a callback method with the property,then you can simply pass null to the PropertyMetadata constructor like I did in the previous snippet).

After registering the property,you’re supposed to add a setter and a getter: in this case, I’ve called them GetLeft and SetLeft in order to comply with the recommendations. Once again, these methods are there as helpers and you can bypass them when writing you code (though I do recommend using them whenever possible).

And that’s really it…you don’t need anything extra for exposing an attached property. Stay tuned for more on Silverlight (there’s still a long road to go!)