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