Search code examples
c#wpfwpfdatagridwpf-style

DataGridCell style of Center is not working


<DataGrid.Columns>
    <DataGridTextColumn Header="Id" Binding="{Binding Id, Mode=TwoWay}" IsReadOnly="True" Width="100">
        <DataGridTextColumn.CellStyle>
            <Style>
                <Setter Property="FrameworkElement.HorizontalAlignment" Value="Center"></Setter>
            </Style>
        </DataGridTextColumn.CellStyle>
    </DataGridTextColumn>
    <DataGridTextColumn Header="Name" Binding="{Binding Name, Mode=TwoWay}" IsReadOnly="True" Width="100">
        <DataGridTextColumn.CellStyle>
            <Style>
                <Setter Property="FrameworkElement.HorizontalAlignment" Value="Center"></Setter>
            </Style>
        </DataGridTextColumn.CellStyle>
    </DataGridTextColumn>
    <DataGridTextColumn Header="Group" Binding="{Binding Group, Mode=TwoWay}" IsReadOnly="True" Width="100">
        <DataGridTextColumn.CellStyle>
            <Style>
                <Setter Property="FrameworkElement.HorizontalAlignment" Value="Center"></Setter>
            </Style>
        </DataGridTextColumn.CellStyle>
    </DataGridTextColumn>
</DataGrid.Columns>

I am trying to apply Center text allignment to the GridCell but it does not work and looks weird. enter image description here


Solution

  • Set the TextAlignment property to Center:

    <DataGridTextColumn Header="Id" Binding="{Binding Id, Mode=TwoWay}" IsReadOnly="True" Width="100">
        <DataGridTextColumn.CellStyle>
            <Style TargetType="DataGridCell">
                <Setter Property="TextBlock.TextAlignment" Value="Center" />
            </Style>
        </DataGridTextColumn.CellStyle>
    </DataGridTextColumn>
    ...