Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Text alignment in DataGrid

Tags:

wpf

xaml

datagrid

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!


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.


for affect all column

 <Window.Resources>
        <Style TargetType="DataGridColumnHeader">
            <Setter Property="HorizontalAlignment" Value="Stretch"/>
            <Setter Property="HorizontalContentAlignment" Value="Center"/>
        </Style>
 </Window.Resources>

In case you want to center the dates in a DataGridTemplateColumn

 <DataGridTemplateColumn SortMemberPath="DataDiNascita" Header="Data di nascita" IsReadOnly="False">
                <DataGridTemplateColumn.CellEditingTemplate>                        
                    <DataTemplate>
                        <DatePicker SelectedDate="{Binding Path=DataDiNascita,Mode=TwoWay}" VerticalAlignment="Center" HorizontalAlignment="Left">                                
                        </DatePicker>                           
                    </DataTemplate>
                </DataGridTemplateColumn.CellEditingTemplate>
                <DataGridTemplateColumn.CellTemplate>                        
                    <DataTemplate>
                        <TextBlock Text="{Binding Path=DataDiNascita,Mode=TwoWay,StringFormat=\{0:dd/MM/yyyy\}}"  VerticalAlignment="Center" HorizontalAlignment="Left">                              
                        </TextBlock>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>