Silverlight StackPanel with VerticalGap and HorizontalGap Properties
[updated 7/12/09 to Silverlight 3 RTW]
If you come to Silverlight with a Flex background, the first time you use a StackPanel you will be disappointed to find that there are no horizontalGap or verticalGap (depending on the Orientation) properties as in the Flex counterparts: VBox and HBox. In Flex these two properties are super useful as they dictate how much space is between each item contained within the Container Control.
1 | <mx:VBox width="100%" height="100%" verticalGap="10" verticalAlign="middle"> |
In Silverlight you have a couple of options but neither is as easy as using a simple property right in the markup. The most direct method is to set the Margin on each of the Children as in:
1 2 3 4 5 6 | <StackPanel Margin="0"> <Rectangle Fill="Red" Width="50" Height="50" Margin="5" /> <Rectangle Fill="Blue" Width="50" Height="50" Margin="5" /> <Rectangle Fill="Green" Width="50" Height="50" Margin="5" /> <Rectangle Fill="Purple" Width="50" Height="50" Margin="5" /> </StackPanel> |
I’m not sure about you but I’d probably tweak that setting a few times to get it right. If you start thinking about using a search and replace utility to change something it starts to smell. Here’s the docs for the Margin property. Above we set all four (left, right, top, bottom) to 5 (pixels in Silverlight, not device independent units).
Another option is to place all the child controls in an ItemsControl and use the ItemContainerStyle property to set the style where you can specify the Margin so you don’t have to specify it on each and every child control. Again, a lot of work when we already have the StackPanel Control.
You could set it in code which is a one stop tweak but its not considered good manners to place code in the View’s code behind.
So, I created a Control that inherits from Panel that exposes these two properties. I started with an example from Silverlight 2 Recipes A Problem-Solution Approach (by: Jit Ghosh , Rob Cameron) that demonstrated a WrapPanel (there’s also one in the Silverlight Extensions, which may be out-of-the-box in a few days with Silverlight 3). I tweaked that Custom Control and sample application to arrive at the StackPanelWithGaps Control. Now I can just do this (after declaring an xmlns for the control’s assembly):
1 2 3 4 5 6 | <lib:StackPanelWithGaps Orientation="Horizontal" HorizontalGap="10"> <Rectangle Fill="Red" Width="50" Height="50" /> <Rectangle Fill="Blue" Width="50" Height="50" /> <Rectangle Fill="Green" Width="50" Height="50" /> <Rectangle Fill="Purple" Width="50" Height="50" /> </lib:StackPanelWithGaps> |
There’s a demo app (again, thanks to the book’s authors) in the code download. Play with the controls on the bottom to adjust the Orientation and Gaps. – Cheers!
Your browser does not support iframes.
[...] Silverlight StackPanel with VerticalGap and HorizontalGap Properties [...]