DataGrid: How to center the title bar and content

Content centered style

<Style
    x:Key="HorizontalAlignedData"
    BasedOn="{StaticResource {x:Type TextBlock}}"
    TargetType="{x:Type TextBlock}">
    <Setter Property="HorizontalAlignment" Value="Center" />
    <Setter Property="VerticalAlignment" Value="Center" />
</Style>

title centering style

<Style TargetType="DataGridColumnHeader">
    <Setter Property="HorizontalContentAlignment" Value="Center" />
    <Setter Property="BorderBrush" Value="#a8a8a8" />
    <Setter Property="Background" Value="#f2f2f2" />
    <Setter Property="FontSize" Value="15" />
    <Setter Property="Padding" Value="5" />
    <Setter Property="Foreground" Value="{StaticResource TextColorGeneral}" />
    <Setter Property="BorderThickness" Value="0,0,1,1" />
</Style>

Realize that each column is displayed proportionally

Set the column width to starswidth="*"


<DataGridTextColumn
    Width="*"
    Binding="{Binding Name}"
    ElementStyle="{StaticResource HorizontalAlignedData}"
    Header="Project"
    IsReadOnly="True" />

Complete demo code


<DataGrid.Columns>

    <DataGridTextColumn
        Width="*"
        Binding="{Binding Name}"
        ElementStyle="{StaticResource HorizontalAlignedData}"
        Header="Project"
        IsReadOnly="True" />

    <DataGridTextColumn
        Width="*"
        Binding="{Binding Value}"
        ElementStyle="{StaticResource HorizontalAlignedData}"
        Header="Outcome"
        IsReadOnly="True" />

    <DataGridTextColumn
        Width="2*"
        Binding="{Binding Tolerance}"
        ElementStyle="{StaticResource HorizontalAlignedData}"
        Header="Task"
        IsReadOnly="True" />

</DataGrid.Columns>

Read More:

Leave a Reply

Your email address will not be published. Required fields are marked *