Text alignment in 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!


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>

As mentioned in other answers:

<Setter Property="HorizontalAlignment" Value="Center" />

HorizontalAlignment

This will affect any other styles such as background. To only center the text use this instead:

<Setter Property="TextAlignment" Value="Center" />

textalign


Maybe just create a style:

<Window.Resources>
    <Style TargetType="DataGridCell">
        <Setter Property="HorizontalAlignment" Value="Center" />
    </Style>
</Window.Resources>  

Edited.

Tags:

Wpf

Xaml

Datagrid