views:

1744

answers:

2

How to add easily a cell padding for a Grid in Silverlight? To set Margins for each cell looks very noisy.

<Grid.RowDefinitions>
  <RowDefinition Height="Auto" />
  <RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
  <ColumnDefinition Width="Auto" />
  <ColumnDefinition Width="*"  />
</Grid.ColumnDefinitions>

<TextBlock Text="Type:" Grid.Column="0" Grid.Row="0"></TextBlock>
<ComboBox Grid.Column="1" Grid.Row="0"></ComboBox>
<TextBlock Text="Length:" Grid.Column="0" Grid.Row="1"  ></TextBlock>
<TextBox  Grid.Column="1"  Grid.Row="1"></TextBlock>

+4  A: 

Someone will probably crucify me for the ugliness of this solution, but you can add Rows and Columns with Height and Width set to twice your padding values in between the actual rows and columns that contain data:

<Grid> 
<Grid.RowDefinitions>
   <RowDefinition Height="Auto" />
   <RowDefinition Height="4" />
   <RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
   <ColumnDefinition Width="Auto" />
   <ColumnDefinition Width="4" />
   <ColumnDefinition Width="*"  />
</Grid.ColumnDefinitions>
<TextBlock Text="test" Grid.Column="0" Grid.Row="0" />
<TextBlock Text="test" Grid.Column="0" Grid.Row="2" />
<TextBlock Text="test" Grid.Column="2" Grid.Row="0" />
<TextBlock Text="test" Grid.Column="2" Grid.Row="2" />
</Grid>
Klay
On the contrary, I have found this to be quite a good solution in the past.
Tim Erickson
I've used this in the past but it drove me nuts, I was forever mis-calculating the correct row and column number to apply to an Element.
AnthonyWJones
@Anthony--I had the same problem while working up the example :) But then, the whole Grid syntax and construction is, in my opinion, exceedingly ugly. I've only ever used a 1x1 grid in production--everything else is StackPanels and Borders.
Klay
Then again, if you remember to always check that the number is even and is twice the number you'd *think* you need, it may not be so bad.
Klay
I find the Grid syntax quite elegant myself, I've often found that when its hard or ugly it turns out I'm not using it for the right purpose.
AnthonyWJones
Not really the solution i looked for, but a nice workaround!
Sven Sönnichsen
+1  A: 

I personally prefer to use margins. To clean it up a little bit, you can refactor them into styles. You could even go one step farther and use an Implicit style manager.

If you really wanted something clean, you could make a padding attached property that would handle the grid loaded event and then set the margins of all of the children.

Jacob Adams