Tuesday, July 24, 2012

WPF DataGrid CellStyle (CenterCellStyle)

This post is part of series called WPF Styles where you can find many different styles for your WPF application.

When your DataGrid contains many different controls, the height of a cell in DataGrid increases accordingly. This make your text to look ugly inside the cell.

DataGrid without CellStyle

As you can see "Imaging" and "Devices" are not aligned to the center of the cell and overall look of DataGrid is ugly. To fix this problem you can apply a simple style that will put the cell content at the middle of the cell.

DataGrid CellStyle applied (aligned to center)

Here is DataGrid CellStyle code:
<Style x:Key="CenterCellStyle" TargetType="{x:Type DataGridCell}">
    <Setter Property="Template">
            <ControlTemplate TargetType="{x:Type DataGridCell}">
                <Grid Background="{TemplateBinding Background}">
                    <ContentPresenter HorizontalAlignment="Center" 
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="Background" Value="Transparent" />
            <Setter Property="BorderBrush" Value="Transparent" />
            <Setter Property="Foreground" Value="Black" />
All you need now to apply this style to specific column or the CellStyle of the DataGrid.
    CellStyle="{StaticResource CenterCellStyle}"

1 comment: