59

How can I align the column data to center in a WPF DataGrid?

Danny Beckett
  • 20,529
  • 24
  • 107
  • 134
Prashant Cholachagudda
  • 13,012
  • 23
  • 97
  • 162
  • 1
    For Silverlight, see [this answer](http://stackoverflow.com/questions/7916226/column-aligment-in-a-silverlight-datagrid/7916301#7916301). – Drew Noakes Oct 27 '11 at 13:10

13 Answers13

106

If you are using DataGridTextColumn you can use the following code snippet:

<Style TargetType="DataGridCell">
     <Style.Setters>
            <Setter Property="TextBlock.TextAlignment" Value="Center" />
     </Style.Setters>
</Style>
Mohammed A. Fadil
  • 9,205
  • 7
  • 50
  • 67
50

It's hard to say without knowing specifics, but here's a DataGridTextColumn that is centered:

<wpf:DataGridTextColumn Header="Name" Binding="{Binding Name}" IsReadOnly="True">
    <wpf:DataGridTextColumn.CellStyle>
        <Style>
            <Setter Property="FrameworkElement.HorizontalAlignment" Value="Center"/>
        </Style>
    </wpf:DataGridTextColumn.CellStyle>
</wpf:DataGridTextColumn>
Kent Boogaart
  • 175,602
  • 35
  • 392
  • 393
24

I started with huttelihut's solution. Unfortunately, that didn't work for me just yet. I tweaked his answer and came up with this (solution is to align the text to the right):

<Resources>
    <Style x:Key="RightAligned" TargetType="TextBlock">
        <Setter Property="HorizontalAlignment" Value="Right"/>
    </Style>
</Resources>

As you can see, I applied the style to a TextBlock, not the DataGridCell.

And then I had to set the Element style, not the Cell style.

ElementStyle="{StaticResource RightAligned}"
Jan
  • 2,168
  • 2
  • 19
  • 28
15

+1 for Kent Boogaart. I ended up doing this, which makes the code slightly less cluttered (and enables me to use the alignment on several columns):

<Resources>
      <Style x:Key="NameCellStyle" TargetType="DataGridCell">
                <Setter Property="HorizontalAlignment" Value="Center" />
      </Style>
</Resources>


<DataGrid.Columns>                           
   <DataGridTextColumn Header="Name" CellStyle="{StaticResource NameCellStyle}" Binding="{Binding Name}"/>                            
    // .. other columns        
</DataGrid.Columns>
Torben Junker Kjær
  • 4,042
  • 4
  • 34
  • 33
  • 2
    +1 for style, but for me `HorizontalAlignment` does not work whereas `HorizontalContentAlignment` does. – Emmanuel May 04 '11 at 08:42
  • You can do the same with a DataGridColumnHeader style and set that as the HeaderStyle. Nice clean solution. – Ed Hartley Jul 08 '20 at 00:47
9

Here's @MohammedAFadil's XAML answer, converted to C# code behind:

var MyStyle = new Style(typeof(DataGridCell)) {
    Setters = {
        new Setter(TextBlock.TextAlignmentProperty, TextAlignment.Center)
    }
};

To apply the Style, set the CellStyle property of the DataGrid, e.g.

var MyGrid = new DataGrid() {
    CellStyle = MyStyle
};
Danny Beckett
  • 20,529
  • 24
  • 107
  • 134
5

Or in code behind:

grid.CellStyle = newCellStyle();

public static Style newCellStyle()
{
    //And here is the C# code to achieve the above
    System.Windows.Style style = new Style(typeof(DataGridCell));
    style.Setters.Add(new System.Windows.Setter
    {
        Property = Control.HorizontalAlignmentProperty,
        Value = HorizontalAlignment.Center
    });
    return style;
}
Hans
  • 61
  • 1
  • 1
5

I ended up having problems with the cell being shifted and looking funky using the accepted answer. I know it's late, but hopefully my findings will help someone. I use:

<DataGridTextColumn.ElementStyle>
     <Style>
          <Setter Property="FrameworkElement.HorizontalAlignment" Value="Center"/>
     </Style>

rather than the CellStyle.

Rachael
  • 1,965
  • 4
  • 29
  • 55
3

If someone is still looking for answer for this, here's what worked for me:

<DataGridTextColumn ...>
    <DataGridTextColumn.CellStyle>
        <Style TargetType="{x:Type DataGridCell}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type DataGridCell}">
                        <Grid Background="{TemplateBinding Background}">
                            <ContentPresenter VerticalAlignment="Center" HorizontalAlignment="Left"/>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </DataGridTextColumn.CellStyle>
</DataGridTextColumn>
KeWiS
  • 41
  • 1
2

For me this one works well

<DataGridTextColumn Width="1*" Binding="{Binding Balance, StringFormat=C} "Header="Balance">
  <DataGridTextColumn.CellStyle>
      <Style>
        <Setter Property="TextBlock.TextAlignment"  Value="Right"/>
      </Style>
   </DataGridTextColumn.CellStyle>
 </DataGridTextColumn>
Bruno Henn
  • 91
  • 3
1

Ok, I used the frameworkElement approach but there was a strange behavior when you try to highlight the row.

I've put another example of WPF Datagrid alignment in this thread!

Community
  • 1
  • 1
Junior Mayhé
  • 16,144
  • 26
  • 115
  • 161
1

My favorite solution is:

<DataGridTextColumn Header="My Column" Binding="{Binding MyDBValue}" Width="100" >
<DataGridTextColumn.CellStyle>
        <Style>
                <Setter Property="FrameworkElement.HorizontalAlignment" Value="Center"/>
        </Style>
</DataGridTextColumn.CellStyle>

Francisco Campos
  • 1,191
  • 8
  • 16
0

Thanks Danny Beckett for converting @MohammedAFadil's XAML answer, converted to C# code. All of my datagrids are set up dynamically, so I can change anything, whenever.

To set up an empty datagrid, with nothing in it and then just bind it to data, just take your datagrid.columns

        var centerTextSetter = new Style(typeof(DataGridCell))
        {
            Setters = { new Setter(TextBlock.TextAlignmentProperty, TextAlignment.Center) }
        };
        DgDbNames.Columns.Add(new DataGridTextColumn()
        {
            Header = "Db Name",
            Binding = new System.Windows.Data.Binding("DbName"),
            IsReadOnly = true,
            Width = new DataGridLength(0.2, DataGridLengthUnitType.Star),
            CellStyle = centerTextSetter
        });
Stephen Himes
  • 655
  • 9
  • 13
0

I really like Bruno's TextBlock.TextAlignment approach. You can use this in conjunction with horizontal alignment and then any background will stretch across the whole grid cell.

e.g. (in VB)

    Dim sty = New System.Windows.Style(GetType(DataGridCell))
    sty.Setters.Add(New Setter(HorizontalAlignmentProperty, HorizontalAlignment.Stretch))
    sty.Setters.Add(New Setter(TextBlock.TextAlignmentProperty, TextAlignment.Right))
    sty.Setters.Add(New Setter(BackgroundProperty, Brushes.LightGray))
Mikey
  • 11
  • 3