【问题标题】:How to center DataGridColumn text (not header) to center?如何将 DataGridColumn 文本(不是标题)居中?
【发布时间】:2016-09-01 07:26:06
【问题描述】:

我有这个DataGrid 结构:

<DataGrid AutoGenerateColumns="False"
                              CanUserAddRows="False"
                              HorizontalContentAlignment="Center"
                              CanUserResizeColumns="False" 
                              CanUserSortColumns="False" 
                              CanUserResizeRows="False"
                              BorderBrush="DimGray" 
                              BorderThickness="1"
                              IsReadOnly="True"
                              ItemsSource="{Binding MatchStats}"
                              HorizontalAlignment="Right"
                              Width="255" 
                              Margin="10, 10, 30, 0">
                    <DataGrid.Columns>
                        <DataGridTextColumn Header="Foo" Binding="{Binding Path = PlayingMatch}"  >
                            <DataGridTextColumn.HeaderStyle>
                                <Style TargetType="{x:Type DataGridColumnHeader}" BasedOn="{StaticResource MetroDataGridColumnHeader}">
                                    <Setter Property="Background" Value="LightGreen" />
                                    <Setter Property="Width" Value="85" />
                                </Style>
                            </DataGridTextColumn.HeaderStyle>
                        </DataGridTextColumn>
                        ...

我需要做的是将行的DataGrid 文本设置为居中。我实际上在标题中管理了这种情况,但我无法对行执行此操作。我在堆栈上看到了其他类似的问题,但所有这些都使用textblock,而且我没有使用任何文本块,你可以在图像中看到什么。

可以这样做吗?

实际结果:

三个0应该居中。

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    在您的 windows.resources 部分添加以下样式

      <Style x:Key="{x:Type DataGridCell}" TargetType="DataGridCell">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type DataGridCell}">
                        <Grid>
                            <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"></ContentPresenter>
                        </Grid>                        
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    

    【讨论】:

      【解决方案2】:

      DataGridTextColumn 是使用 TextBlock 构建的。因此,当未更改时(如您提供的代码),它将与 TextBlock.TextAlignment 一起使用。

      <Style TargetType="{x:TypeDataGridCell}">
          <Style.Setters>
              <Setter Property="TextBlock.TextAlignment" Value="Center" />
          </Style.Setters>
      </Style>
      

      【讨论】:

        猜你喜欢
        • 2020-09-14
        • 2016-04-02
        • 2017-01-29
        • 2011-09-12
        • 1970-01-01
        • 1970-01-01
        • 2018-04-17
        • 2020-10-15
        • 1970-01-01
        相关资源
        最近更新 更多