Brendan Enrick

Daily Software Development

Silverlight Attached Properties

One cool feature of XAML is the concept of an attached property. These properties are a way of extending the properties of an element in XAML. By this I don't mean that you can add any arbitrary extra property to an element. What I mean is that child elements have certain properties from their parents attached to them. This is often used as a way of allowing a child element to interact with a parent.

A couple of examples of what I mean can be found in the DockPanel and the Canvas elements. Some attached properties you will find from the Canvas element are Canvas.Top, Canvas.Left, and Canvas.ZOrder. These three let you control the location of the child element within the canvas. A DockPanel element gives DockPanel.Dock, because it is important to know where on the DockPanel your child element is docked.

You have probably noticed by now the naming of these attached properties. They are named in the following way.

ElementName.PropertyName

Here are some examples of how to use these.

<DockPanel>
  <Button DockPanel.Dock="Left"/>
</DockPanel>

<Canvas>
  <Ellipse Width="100" Height="100" Fill="Black"
    Canvas.Left="25" Canvas.Top="25" />
</Canvas>

Notice I've docked the button to the left of the DockPanel and the Eliipse has been positioned away from the left and away from the top of the canvas.

It would be a nightmare to try to control positioning of elements inside of the canvas anywhere but on the specific element, and the attached properties allow this to happen. I think they are quote cool.

Comments (1) -

  • 2/6/2009 8:55:57 PM | Reply

    No matter how much I try to justify them, I still believe that in most cases it could have been done better behind the scenes. Why do I have to explicitly specify the parent element to set a value that only makes sence to the child element? What if I wanted to change the parent, do I have to go change it all over the place if I had 100 child elements?


Loading