How to center the content of cells in a data grid?

后端 未结 10 948
春和景丽
春和景丽 2020-12-30 22:58

I set the min height of a datagrid that way:


After feeding the datagrid with datas, the text in each c

相关标签:
10条回答
  • 2020-12-30 23:10

    This style will set the VerticalAlignment to Center for all DataGridCells without needing to be applied explicitly.

    <Style TargetType="DataGridCell">
        <Style.Resources>
            <Style TargetType="ContentPresenter">
                <Setter Property="VerticalAlignment" Value="Center" />
            </Style>
        </Style.Resources>
    </Style>
    

    I find this to be the most elegant solution.

    0 讨论(0)
  • 2020-12-30 23:11

    use ElementStyle

     <DataGridTextColumn ElementStyle="{StaticResource Centering}"/>
    
      <Style x:Key="Centering" TargetType="{x:Type TextBlock}">
           <Setter Property="HorizontalAlignment" Value="Center" />
      </Style>
    
    0 讨论(0)
  • 2020-12-30 23:12

    Final solution:

    <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>
    
    0 讨论(0)
  • 2020-12-30 23:12

    Modify your style tag like this.....

     <Style x:Key="CellTextCentre" TargetType="DataGridCell">
        <Setter Property="TextBlock.TextAlignment" Value="Center"></Setter>
        <Setter Property="TextBlock.VerticalAlignment" Value="Center"></Setter> 
     </Style>
    
    0 讨论(0)
  • 2020-12-30 23:13

    The following code will center the contents of cells in DataGrid:

    <Style TargetType="DataGridCell">
        <Setter Property="TextBlock.TextAlignment" Value="Center" />
    </Style>
    
    0 讨论(0)
  • 2020-12-30 23:15

    Here is a slightly longer version of Arpit Shah's answer.

    <DataGrid AutoGenerateColumns="False" IsReadOnly="True" ItemsSource="{Binding Rows}">
        <DataGrid.Resources>
            <Style x:Key="RightAligned" TargetType="DataGridCell">
                <Setter Property="HorizontalAlignment" Value="Right" />
            </Style>
        </DataGrid.Resources>
        <DataGrid.Columns>
            <DataGridTextColumn CellStyle="{StaticResource RightAligned}" 
                                Binding="{Binding Path=Quantity, Mode=OneWay}" 
                                Header="Quantity" Width="60" />
            <DataGridTextColumn Binding="{Binding Path=Category, Mode=OneWay}" 
                                Header="Category" Width="150" />
        </DataGrid.Columns>
    </DataGrid>
    
    0 讨论(0)
提交回复
热议问题