Text alignment in a WPF DataGrid
How can I align the column data to center in a WPF DataGrid
?
Solution 1:
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:
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:
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:
+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:
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
};