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

后端 未结 10 949
春和景丽
春和景丽 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:18

    This below code display datagrid cell conent in center..

    <Style x:Key="DataGridCellStyle" TargetType="DataGridCell">
                <!--DISPLAY CONTENT IN MIDDLE-->
                <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:23

    Try setting the DataGrid's Vertical and HorizontalContentAlignment to Center

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

    If that doesn't work, you can use the solution in this answer. It uses a style that aligns the DataGrid cell contents

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

    you can use styles. i add a sample for DataGridCheckBoxColumn, i hope it put you in the right direction.

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

    Here a better approach to center the content vertically:

    <Style TargetType="{x:Type DataGridCell}" BasedOn="{StaticResource {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)
提交回复
热议问题