Warm tip: This article is reproduced from serverfault.com, please click

Set a padding on dataGridCells in WPF

发布于 2011-03-09 13:52:39

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.

Questioner
David
Viewed
0
Fredrik Hedblad 2011-03-09 22:18:59

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>