Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a padding on dataGridCells in WPF

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.

like image 311
David Avatar asked Mar 09 '11 13:03

David


2 Answers

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> 
like image 167
Fredrik Hedblad Avatar answered Oct 01 '22 10:10

Fredrik Hedblad


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)

like image 27
Scott Brickey Avatar answered Oct 01 '22 10:10

Scott Brickey