I miss the HTML-cellspacing in WPF. Im trying to implement something similar in WPF's Grid by making a custom Grid-class overriding from Grid and then modifying MeasureOverride and ArrangeOverride to get the behaviour I want. Which is that each cell in a grid should have a fixed spacing (not padding) to each other cell. How could this be done?
I found this blog post about creating a custom grid panel that handles spacing between cells: http://daniel-albuschat.blogspot.dk/2011/07/gridlayout-for-wpf-escape-margin-hell.html
You could probably write your own panel, or perhaps even a Grid descendant, that does your own layout with cell spacing. It would be a fair bit of work.
Here's what I usually do instead, to achieve the same thing. Suppose I want a cell spacing of 3 pixels. You can accomplish that by applying a 1.5 pixel margin to each cell (so the total space between a cell and its neighbor is 1.5 + 1.5 = 3 pixels), and then another 1.5 pixel margin around the entire Grid so the outer margin is correct (1.5 pixel margin around the cell + 1.5 margin around the Grid = 3 pixels). The XAML looks like this:
<Grid Margin="1.5">
...
<Label Grid.Row="0" Grid.Column="0" Margin="1.5">...</Label>
<TextBox Grid.Row="0" Grid.Column="1" Margin="1.5">...</TextBox>
...
</Grid>
It's ugly but it works.
If most of the controls in your Grid are of the same type (e.g. if it's all Labels, or all Labels and TextBoxes), then you can use styles, instead of declaring and re-declaring the Margin on every element in the grid:
<Grid Margin="1.5">
<Grid.Resources>
<Style TargetType="Label">
<Setter Property="Margin" Value="1.5"/>
</Style>
<Style TargetType="TextBox">
<Setter Property="Margin" Value="1.5"/>
</Style>
</Grid.Resources>
...
<Label Grid.Row="0" Grid.Column="0">...</Label>
<TextBox Grid.Row="0" Grid.Column="1">...</TextBox>
...
</Grid>
Actually, I've found in practice that I often want uneven margins -- for example, I may want a 3-pixel margin around the top, left, and right, but no margin on the bottom (because the controls below it already have a margin of their own). So I usually don't end up using 1.5 pixels all around; I usually end up with something more complex. So I can see why they didn't add a CellSpacing; it would make the simple cases simpler, but would be useless in more complicated layouts.
But half-margins-all-around is a quick way to achieve CellSpacing, and then you can tweak the margins if you need something fancier.
I found this blog post about creating a custom grid panel that handles spacing between cells: http://daniel-albuschat.blogspot.dk/2011/07/gridlayout-for-wpf-escape-margin-hell.html
You may interested with my answer here, supports uniform border and cellspacing for each child in a custom grid:
You're looking for the Margin property. You can style the DataGridCell class.
<Style TargetType="{x:Type toolkit:DataGridCell}">
<Setter Property="Margin" Value="3" />
</Style>
© 2022 - 2024 — McMap. All rights reserved.