Today we are looking at a second way to lay out your interface in Silverlight. This will be far more familiar to the CSS fanatics out there. The primary concept is simple…we’ll be using a StackPanel control to position our elements.
For those of you less familiar with CSS, this is more of a flow-based layout. As the size of the Silverlight container grows and shrinks, you will find that the elements will move to accomodate that space. I, personally, would not recommend approaching your entire interface with this technique, but it certainly makes sense for small portions, like navigations and lists of data.
Most of our positions will be determined by manipulating the margins of the individual elements on the page. In doing so, we can place our elements specific distances apart without having to specify their exact position on that page.
In the example below, I have 6 buttons that I want to arrange in a 3×2 block. I start with an outer stack panel that, by default, will stack my elements vertically. However, I want to have two rows of 3 buttons each, so I am going to nest two more stack panels. Each of these will have the Orientation attribute of the StackPanel set to Horizontal, to create the rows.
For demonstration purposes, I also modified the margins of a few of the buttons, just to show that we are merely stacking these elements. This is not a grid, or table, and certainly not absolute positioning. These elements are merely stacked, either horizontally or vertically, with margins as the leverage to move things around a bit.
NOTE: I have a major complaint about how margins were implemented in Silverlight.
Again, for those of you familiar with CSS, the de-facto standard for specifying margin sizes was one of two formats:
margin:0 10px 0 10px;
Each of those examples would have given you a 10 pixel margin on both the left and right of the element you were styling. In the second example, we are using a bit of shorthand to specify ALL of the margins in one line. They start with the top, and go clockwise. margin:Top Right Bottom Left;
In the margin implementation for Silverlight, it would appear that they also offer a shorthand version for margins (actually, the only version is shorthand), and they did not follow the standard convention mentioned above. Instead, they chose to use Margin=”Left, Top, Right, Bottom”. I’ve not yet talked with the team to see why this convention was chosen over something more familiar to developers, but if I can find an answer, I will post it here.