Text alignment in a WPF DataGrid

C#.NetWpfXamlWpftoolkit

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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>

Solution 2 - C#

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>

Solution 3 - C#

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}"

Solution 4 - C#

+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>

Solution 5 - C#

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
};

Solution 6 - C#

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;
}

Solution 7 - C#

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.

Solution 8 - C#

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>

Solution 9 - C#

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!

Solution 10 - C#

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>

Solution 11 - C#

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>

Solution 12 - C#

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
        });

Solution 13 - C#

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))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPrashant CholachaguddaView Question on Stackoverflow
Solution 1 - C#Mohammed A. FadilView Answer on Stackoverflow
Solution 2 - C#Kent BoogaartView Answer on Stackoverflow
Solution 3 - C#JanView Answer on Stackoverflow
Solution 4 - C#T.J.KjaerView Answer on Stackoverflow
Solution 5 - C#Danny BeckettView Answer on Stackoverflow
Solution 6 - C#HansView Answer on Stackoverflow
Solution 7 - C#RachaelView Answer on Stackoverflow
Solution 8 - C#KeWiSView Answer on Stackoverflow
Solution 9 - C#Junior MayhéView Answer on Stackoverflow
Solution 10 - C#Francisco CamposView Answer on Stackoverflow
Solution 11 - C#Bruno HennView Answer on Stackoverflow
Solution 12 - C#Stephen HimesView Answer on Stackoverflow
Solution 13 - C#MikeyView Answer on Stackoverflow