Text alignment in DataGrid
I'm programming by WPF. I need a way to make center content of cells, in DataGrid control. I use this code also:
<DataGrid x:Name="dg1" HorizontalAlignment="Left" Margin="10,10,0,0"
VerticalAlignment="Top" Height="360" Width="498"
FontFamily="2 Badr" FontSize="18"
AlternatingRowBackground="LightCoral" FlowDirection="RightToLeft"
HorizontalContentAlignment="Center" VerticalContentAlignment="Center"
Background="{x:Null}"/>
What is wrong?
You need set DataGridCell style
<DataGrid>
<DataGrid.Columns>
<DataGridTextColumn>
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="HorizontalAlignment" Value="Center" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
For those who need to format only one dynamic DataGrid column in VB.NET from a custom XAML style:
In Application.xaml:
<Application.Resources>
<ResourceDictionary>
<Style x:Key="DataGridCellCentered" TargetType="DataGridCell">
<Setter Property="TextBlock.TextAlignment" Value="Center" />
</Style>
</ResourceDictionary>
</Application.Resources>
In VB.NET code:
Me.MyDataGrid.Columns(5).CellStyle = TryFindResource("DataGridCellCentered")
Regards!