Set a padding on dataGridCells in WPF
The problem is that the Padding
isn't transfered to the Border
that's in the Template for DataGridCell
. You can edit the Template and add the TemplateBinding for Padding
<DataGrid ...> <DataGrid.CellStyle> <Style TargetType="DataGridCell"> <Setter Property="Padding" Value="20"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type DataGridCell}"> <Border Padding="{TemplateBinding Padding}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True"> <ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> </DataGrid.CellStyle> <!--...--></DataGrid>
Here's a cleaner method (my opinion) that combines the approach from David
<Resources> <Style x:Key="ColumnElementStyle" TargetType="TextBlock"> <Setter Property="Margin" Value="5,0,10,0" /> </Style></Resources>
then...
<DataGridTextColumn ElementStyle="{StaticResource ColumnElementStyle}" /><DataGridTextColumn ElementStyle="{StaticResource ColumnElementStyle}" />
(in my case, my rows are readonly, so no EditingStyle)
Almost 5 years later, since this question seems to still be of use (it is still getting upvotes) and since it has been requested, here is the solution I used (with the ElementStyle) on a TextColumn (but you can do the same for any type of DataGridColumn):
I did it all in code behind:
class MyTextColumn : DataGridTextColumn{ public MyTextColumn() { ElementStyle = new Style(typeof(TextBlock)); EditingElementStyle = new Style(typeof(TextBox)); ElementStyle.Setters.Add(new Setter(FrameworkElement.MarginProperty, new Thickness(3))); EditingElementStyle.Setters.Add(new Setter(Control.PaddingProperty, new Thickness(0, 1, 0, 1))); }}
But if you want to do it directly in xaml:
<DataGrid.Columns> <DataGridTextColumn> <DataGridTextColumn.ElementStyle> <Style TargetType="TextBlock"> <Setter Property="Margin" Value="3"/> </Style> </DataGridTextColumn.ElementStyle> <DataGridTextColumn.EditingElementStyle> <Style TargetType="TextBox"> <Setter Property="Padding" Value="0 1 0 1"/> </Style> </DataGridTextColumn.EditingElementStyle> </DataGridTextColumn></DataGrid.Columns>