qing xu
qing xu

Reputation: 55

How to vertically center rows' contents in a WPF DataGrid?

I want to make the data record's VerticalAlignment=Center in DataGrid. By default,the data record's VerticalAlignment=Top, It looks uglily. Can you provide me this style?

I define my style in App.xaml file. The following is my current DataGrid style:

    <Style x:Key="DataGridView" TargetType="DataGrid">
        <Setter Property="AlternatingRowBackground" Value="AliceBlue"></Setter>
        <Setter Property="AlternationCount" Value="1"></Setter>
        <Setter Property="AutoGenerateColumns" Value="False"></Setter>
        <Setter Property="GridLinesVisibility" Value="Horizontal"></Setter>
        <Setter Property="VerticalGridLinesBrush" Value="DarkGray"></Setter>
        <Setter Property="HorizontalGridLinesBrush" Value="DarkGray"></Setter>
        <Setter Property="RowHeight" Value="32"></Setter>
    </Style>

Upvotes: 3

Views: 16330

Answers (1)

Pavel Gatilov
Pavel Gatilov

Reputation: 7661

Try setting VerticalContentAlignment="Center" on the DataGrid:

<DataGrid VerticalContentAlignment="Center">
  ...
</DataGrid>

or you can add a setter to your style:

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

When applied to ItemsControls, this property usually modifies alignment of each individual item container. In your case, this should make all rows align their contents to center.

UPDATE

Seems like the WPF built-in DataGrid doesn't follow the rule.

The solution depends on the type of the columns you use.

For DataGridTemplateColumn use a CellTemplate like this:

<DataTemplate>
    <!--Substitute the TextBlock by the actual cell content, but don't drop VerticalAlignment-->
  <TextBlock VerticalAlignment="Center" Text="{Binding Text}"/>
</DataTemplate>

For DataGridTextColumn, set ElementStyle:

<Style>
  <Setter Property="FrameworkElement.VerticalAlignment" Value="Center"/>
</Style>

I've tried this on DataGridTextColumn, but the property is from its parent DataGridBoundColumn, so should work for DataGridCheckBoxColumn and DataGridHyperlinkColumn also.

Update 2

BTW, there's another solution.

Upvotes: 9

Related Questions