How can I align the column data to center in a WPF DataGrid
?
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;
}
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!
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.
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>
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))
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>