For WPF/Silverlight layout, is it better to use a Grid with lots of rows and columns, or tons of Stackpanels?
7 Answers
You should use a Grid if you need things to line up horizontally and vertically. Use a StackPanel to create a row or column of things when those things don't need to line up with anything else.
However, don't limit yourself to those two options. In particular, have a look at the DockPanel. It's slightly more complex than a StackPanel, but its markup isn't as cluttered as the Grid. Here's a good article on the DockPanel:
I don't think Grid is a better idea.
for example , if you want to insert a row to existing Grid layout document (in the middle)
there exising row is 1,2,3,4 , then the requirement is insert new row between 1 and 2.
then you had to change 2,3,4 to 3,4,5 (find all tag an change....)
think about if one row have 3 - 5 columns... it's a dirty job to reorder all digital.!!!
I prefer the StackPanel because I find it easier to make changes when inserting new elements, rows or columns. With a grid you need to read row numbers and column numbers to find out where you are. With a StackPanel you just follow the nesting, this is easier and less messy than a grid.
For example, in a XAML page, I use a horizontal stack panel like a parent grid, then if I need a column, I have a separate "vertical" stackpanel nested. This way a horizontal stackpanel becomes a "grid" and the nested vertical StackPanel's become the columns. I find this easier to read and modify that rows and columns in a grid.
Both have strength (Grid/Stackpanel). Problem with Grid is the lines restructuring. The problem with Stackpanel is that no table structure (fixed columns width). So I think that is a good solution about this problems :-)
Definition styles
<Page.Resources>
<Style x:Key="LabelCol1" TargetType="Label">
<Setter Property="Width" Value="200" />
</Style>
<Style x:Key="EditCol2" TargetType="TextBox">
<Setter Property="Width" Value="250" />
<Setter Property="TextWrapping" Value="Wrap" />
<Setter Property="Margin" Value="3" />
</Style>
<Style x:Key="ButtonCol3" TargetType="Button">
<Setter Property="Width" Value="120" />
<Setter Property="Margin" Value="3" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="HorizontalContentAlignment" Value="Center" />
</Style>
</Page.Resources>
And using styles into Stackpanel
<StackPanel>
<StackPanel Orientation="Horizontal">
<Label Style="{StaticResource LabelCol1}" Content="Solution path" />
<TextBox Style="{StaticResource EditCol2}" />
<Button Style="{StaticResource ButtonCol3}" Content="Open..." />
</StackPanel>
<StackPanel Orientation="Horizontal">
<Label Style="{StaticResource LabelCol1}" Content="Solution name" />
<TextBox Style="{StaticResource EditCol2}" />
</StackPanel>
</StackPanel>