如何将数据网格中的内容集中在一起?

Fra*_*ois 21 wpf datagrid row alignment

我设置数据网格的最小高度:

<DataGrid MinRowHeight="40">
Run Code Online (Sandbox Code Playgroud)

在使用数据为数据网格提供数据后,每个单元格中的文本都是顶部和左侧对齐的.我找不到一种简单的方法来集中文本.

这样做有什么建议吗?

Fra*_*ois 40

最终解决方案

<Style x:Key="DataGridContentCellCentering" TargetType="{x:Type DataGridCell}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type DataGridCell}">
                <Grid Background="{TemplateBinding Background}">
                    <ContentPresenter VerticalAlignment="Center" />
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
Run Code Online (Sandbox Code Playgroud)

  • 如果您的网格使用DataGridTextColumn以外的列,这是正确的解决方案.如果网格上有模板化列,TextBlock样式解决方案将在文本下方添加一行.如果有人能解释这段代码在做什么...... (3认同)

小智 19

以下代码将以DataGrid中的单元格内容为中心:

<Style TargetType="DataGridCell">
    <Setter Property="TextBlock.TextAlignment" Value="Center" />
</Style>
Run Code Online (Sandbox Code Playgroud)


bli*_*eis 9

你可以使用样式.我为DataGridCheckBoxColumn添加了一个示例,我希望它能让你朝着正确的方向前进.

<DataGridCheckBoxColumn Header="is active" IsReadOnly="False">
      <DataGridCheckBoxColumn.ElementStyle>
            <Style TargetType="CheckBox">
                 <Setter Property="VerticalAlignment" Value="Center"/>
                  <Setter Property="HorizontalAlignment" Value="Center"/>
             </Style>
      </DataGridCheckBoxColumn.ElementStyle>
      <DataGridCheckBoxColumn.Binding>
             <Binding Path="ISACTIVE" ValidatesOnDataErrors="True" Converter="{StaticResource MyBoolToIsActiveConverter}" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged"
                                 NotifyOnValidationError="True" ValidatesOnExceptions="True">
                        </Binding>
                    </DataGridCheckBoxColumn.Binding>
                </DataGridCheckBoxColumn>
Run Code Online (Sandbox Code Playgroud)


Mey*_*ini 9

使用元素样式

 <DataGridTextColumn ElementStyle="{StaticResource Centering}"/>

  <Style x:Key="Centering" TargetType="{x:Type TextBlock}">
       <Setter Property="HorizontalAlignment" Value="Center" />
  </Style>
Run Code Online (Sandbox Code Playgroud)


Rac*_*hel 6

尝试将DataGrid的Vertical和Horizo​​ntalContentAlignment设置为Center

<DataGrid VerticalContentAlignment="Center" HorizontalContentAlignment="Center" />
Run Code Online (Sandbox Code Playgroud)

如果这不起作用,您可以使用此答案中的解决方案.它使用一种样式来对齐DataGrid单元格内容


The*_*lon 5

此样式将为所有s 设置VerticalAlignment为,无需显式应用。CenterDataGridCell

<Style TargetType="DataGridCell">
    <Style.Resources>
        <Style TargetType="ContentPresenter">
            <Setter Property="VerticalAlignment" Value="Center" />
        </Style>
    </Style.Resources>
</Style>
Run Code Online (Sandbox Code Playgroud)

我发现这是最优雅的解决方案。