I’m really on this “Attached Property” kick. I’m probably totally over using them, but I think it’s such a powerful tool when used in the right scenario. I’m not really sure what the right scenario actually is, but I keep running into situations where to me they just make sense. Also there’s something about adding behavior to objects without actually inheriting from them that gives me a sense that I’m doing something really cool, cutting edge, and adventerous…alright that’s a little ridiculous. Moving on…
So I had posted a question on StackOverflow (by the way this is such an awesome site) and also wrote here about finding the best approach to applying styles to a large amount of controls. I spent an hour or so on the phone with Karl Shifflett discussing the pro’s and con’s of the various approaches to take which I wont re-hash here. I finally landed on this idea that uses my good buddy DependencyProperty.RegisterAttached.
What I’ve done is create 4 styles in a resource dictionary
- A style for the containing panel (i.e. Grid, StackPanel, etc.)
- A style for the first item(s)
- A style for the last items(s)
- A style for all the items in between
The reason I create different styles is that depending on where the object is in the panel I may want to apply more or less margin, or to different amounts on different sides. Obviously this is just one particular scenario, but you get the point. Then I set the the attached property on the containing grid like this (can also be a StackPanel/DockPanel):
Essentially what the attached property does is iterates through all the children in the Panel and applies one of the specified styles to each element. Care is taken not to override any explicit styles set on any child objects.
Here is a full example including the code for the attached property. Make sure you change the extension from .doc to .zip.