Set a padding on dataGridCells in WPF

David picture David · Mar 9, 2011 · Viewed 47k times · Source

simple question: How can I set a padding on a dataGridCell in WPF? (either one at a time or on all cells, I don't care)

I have tried using the DataGrid.CellStyle property by adding a setter on the DataGridCell.Padding property as well as using the DataGridColumn.CellStyle property in the same way with no effect.

I also tried using the DataGridColumn.ElementStyle property with no more luck.

I'm kind of stuck there, has anyone managed to get a padding applied on a dataGridCell?

NB: I'll add that no, I cannot use transparent borders to do this, since I already use the border properties for something else. I also cannot use the margin property (which seems to work, surprisingly enough) as I use the background property and I don't want any "blank" space between my cells.

Answer

Fredrik Hedblad picture Fredrik Hedblad · Mar 9, 2011

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>