Saturday 23 January 2010

Attached properties in Silverlight

I'm pleasantly surprised by the existence of attached properties in Silverlight. They provide a neat point of extension for properties in child-parent relation between components. It may have been better if they called it "metadata properties" or similar (it would certainly bring my mind into correct direction) though. The example in the book I'm reading is not actually very impressive (namely Grid.Row, for which probably a couple of other options exist) but I can see how the mechanism behind this may be useful when desiging my own app.


The idea is simple - when placing an element in XAML you can place an attribute, say Grid.Row="value". Internally, it's going to get translated into a static call to Grid.SetRow(caller, value), and in this particular case in turn will call caller.SetValue(Grid.RowProperty, value). Parent object then can call getValue on the child to get the value. Nice decoupling and no need to implement any special methods on the classes that are going to be contained in the parent. The child doesn't even have to be aware of what properties are set and how are they going to be used.