Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center the content of cells in a data grid?

I set the min height of a datagrid that way:

<DataGrid MinRowHeight="40">

After feeding the datagrid with datas, the text in each cell is top and left aligned. I could not find an easy way to center that text.

Any suggestions for doing that?

like image 701
Francois Avatar asked May 20 '11 12:05

Francois


3 Answers

Final solution:

<Style x:Key="DataGridContentCellCentering" TargetType="{x:Type DataGridCell}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type DataGridCell}">
                <Grid Background="{TemplateBinding Background}">
                    <ContentPresenter VerticalAlignment="Center" />
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
like image 181
Francois Avatar answered Nov 04 '22 05:11

Francois


The following code will center the contents of cells in DataGrid:

<Style TargetType="DataGridCell">
    <Setter Property="TextBlock.TextAlignment" Value="Center" />
</Style>
like image 26
lea Avatar answered Nov 04 '22 05:11

lea


use ElementStyle

 <DataGridTextColumn ElementStyle="{StaticResource Centering}"/>

  <Style x:Key="Centering" TargetType="{x:Type TextBlock}">
       <Setter Property="HorizontalAlignment" Value="Center" />
  </Style>
like image 9
Meysam Chegini Avatar answered Nov 04 '22 06:11

Meysam Chegini