在 DataGridTextColumn 中为 TextBlock 创建样式 [英] Create style for TextBlock in DataGridTextColumn
问题描述
我想创建一个全局样式,将 VerticalAlignment
设置为 Center
,用于 DataGrid
内的所有 TextBlock
控件> 或在 DataGridTextColumn
内.
I want to create a global style that sets the VerticalAlignment
to Center
for all TextBlock
controls inside a DataGrid
or inside a DataGridTextColumn
.
我不想将以下内容复制到每个 DataGridTextColumn
中,因为它感觉重复.
I don't want to copy the following into every DataGridTextColumn
because it feels repetitive.
<DataGridTextColumn Header="Some Property" Binding="{Binding SomeProperty}">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="VerticalAlignment" Value="Center"></Setter>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
我尝试了以下类似的方法,但它不起作用,因为 DataGridTextColumn
不是从 FrameworkElement
或 FrameworkContentElement
继承的.DataGrid
本身可以,但我尝试的任何进一步包装都会导致错误:
I tried something like the following but it doesn't work because DataGridTextColumn
does not inherit from FrameworkElement
or FrameworkContentElement
. DataGrid
itself does but any further wrapping I try leads to errors:
<Style TargetType="DataGridTextColumn">
<Setter Property="ElementStyle">
<Setter.Value>
<Style TargetType="TextBlock">
<Setter Property="VerticalAlignment" Value="Center"/>
</Style>
</Setter.Value>
</Setter>
</Style>
推荐答案
你可以定义一个 CellStyle
如下:
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>
并将其分配给 DataGrid:CellStyle="{StaticResource DataGridCellStyle}"
.这样,您的所有单元格都会以内容为中心.
And assign it to the DataGrid: CellStyle="{StaticResource DataGridCellStyle}"
.
In this way all your cells will have content centered.
编辑:以上代码来自我的一个项目,还包含删除 DataGrid 中网格线的代码.您可以通过将模板中的 Grid
更改为 Border
来恢复它们.像这样:
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>
这篇关于在 DataGridTextColumn 中为 TextBlock 创建样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!