在DataGridTextColumn中为TextBlock创建样式 [英] Create style for TextBlock in DataGridTextColumn
问题描述
我想创建一个全局样式,将所有的
控件内的 VerticalAlignment
设置为 Center
TextBlock DataGrid
或$ code> 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
如下:
<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屋!