Как вертикально центрировать содержимое строк в WPF DataGrid?


Я хочу сделать запись данных VerticalAlignment=Center в DataGrid. По умолчанию запись данных VerticalAlignment=Top выглядит уродливо. Можете ли вы предоставить мне этот стиль?

Я определяю свой стиль в приложении.файл XAML. Ниже приведен мой текущий стиль DataGrid:

    <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>
1 3

1 ответ:

Попробуйте установить VerticalContentAlignment="Center" на DataGrid:

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

Или вы можете добавить сеттер в свой стиль:

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

При применении к ItemsControls это свойство обычно изменяет выравнивание каждого отдельного контейнера элемента. В вашем случае это должно заставить все строки выровнять их содержимое по центру.

Обновить

Похоже, что встроенный WPF DataGrid не следует правилу.

Решение зависит от типа используемых столбцов.

Для DataGridTemplateColumn используйте a CellTemplate Вот так:

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

Для DataGridTextColumn, set ElementStyle:

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

Я пробовал это на DataGridTextColumn, но свойство от его родителя DataGridBoundColumn, так что должно работать для DataGridCheckBoxColumn и DataGridHyperlinkColumn также.

Обновление 2

Кстати, Есть еще одно решение.