Create style for TextBlock in DataGridTextColumn

荒凉一梦 提交于 2019-11-29 03:45:54

You can define a CellStyle as below:

<Style x:Key="DataGridCellStyle" TargetType="DataGridCell">
    <Setter Property="FocusVisualStyle" Value="{x:Null}" />
    <Setter Property="BorderThickness" Value="0"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type DataGridCell}">
                <Grid Background="{TemplateBinding Background}">
                    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

And assign it to the DataGrid: CellStyle="{StaticResource DataGridCellStyle}". In this way all your cells will have content centered.

EDIT: The above code is from one of my projects and also contains the code to remove grid lines in the DataGrid. You can get them back by changing Grid to Border in the template. Like this:

<Setter Property="Template">
    <Setter.Value>
        <ControlTemplate TargetType="{x:Type DataGridCell}">
            <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
                <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
            </Border>
        </ControlTemplate>
    </Setter.Value>
</Setter>

Create a style as a static resource

<UserControl.Resources>
    <Style x:Key="verticalCenter" TargetType="{x:Type TextBlock}">
        <Setter Property="VerticalAlignment" Value="Center" />
    </Style>
</UserControl.Resources>

Then you can assign it to the ElementStyle of the DataGridTextColumn

<DataGridTextColumn ElementStyle="{StaticResource verticalCenter}" />
Dwsgg

Just use the DataGridTemplateColumn:

<DataGridTemplateColumn Width="SizeToCells">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock HorizontalAlignment="Center" Width="100" Height="20"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!