我想使数据记录的VerticalAlignment=Center
在DataGrid。默认情况下,数据记录是VerticalAlignment=Top
,看起来很丑。你能提供给我这个款式吗?
我在App.xaml文件中定义我的样式。以下是我当前的DataGrid样式:
<Style x:Key="DataGridView" TargetType="DataGrid">
<Setter Property="AlternatingRowBackground" Value="AliceBlue"></Setter>
<Setter Property="AlternationCount" Value="1"></Setter>
<Setter Property="AutoGenerateColumns" Value="False"></Setter>
<Setter Property="GridLinesVisibility" Value="Horizontal"></Setter>
<Setter Property="VerticalGridLinesBrush" Value="DarkGray"></Setter>
<Setter Property="HorizontalGridLinesBrush" Value="DarkGray"></Setter>
<Setter Property="RowHeight" Value="32"></Setter>
</Style>
尝试在DataGrid
上设置VerticalContentAlignment="Center"
:
<DataGrid VerticalContentAlignment="Center">
...
</DataGrid>
或者你可以给你的样式添加setter:
<Setter Property="VerticalContentAlignment" Value="Center"/>
当应用于ItemsControl
时,该属性通常会修改每个单独的项目容器的对齐方式。在您的示例中,这应该使所有行将其内容对齐到居中。
似乎WPF内置的DataGrid
不遵循规则。
解决方案取决于您使用的列的类型。
对于DataGridTemplateColumn
,使用CellTemplate
:
<DataTemplate>
<!--Substitute the TextBlock by the actual cell content, but don't drop VerticalAlignment-->
<TextBlock VerticalAlignment="Center" Text="{Binding Text}"/>
</DataTemplate>
对于DataGridTextColumn
,设置ElementStyle
:
<Style>
<Setter Property="FrameworkElement.VerticalAlignment" Value="Center"/>
</Style>
我已经在DataGridTextColumn
上尝试过了,但是该属性来自它的父DataGridBoundColumn
,所以也应该适用于DataGridCheckBoxColumn
和DataGridHyperlinkColumn
。
更新2
顺便说一下,还有一个解决办法。