WPF DataGrid样式
通过设置DataGrid样式来实现不同的显示效果,因为DataGrid 属性比较多,控制的样式也不一样,这里记录一下,以备忘记。
总结:
- DataGridCell 通过设置样式,控制数据在数据单元格中垂直居中显示
- DataGrid.RowStyle 样式来设置数据行显示样式
- DataGrid.ColumnHeaderStyle 来设置标题栏样式
项目中的代码片段
<DataGrid x:Name="dgSJGZJL" Grid.Row="2"
HeadersVisibility="None"
Background="Transparent"
GridLinesVisibility="None"
Foreground="White"
ScrollViewer.HorizontalScrollBarVisibility="Hidden"
ScrollViewer.VerticalScrollBarVisibility="Hidden"
AutoGenerateColumns="False"
CanUserAddRows="False"
>
<!--设置标题行标题水平居中显示-->
<DataGrid.ColumnHeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="Background" Value="Transparent" />
<Setter Property="Foreground" Value="Orange" />
<Setter Property="FontWeight" Value="Bold" />
<Setter Property="HorizontalContentAlignment" Value="Center" />
</Style>
</DataGrid.ColumnHeaderStyle>
<!--控制数据行中的数据垂直居中显示-->
<DataGrid.Resources>
<Style TargetType="DataGridCell">
<Setter Property="VerticalContentAlignment" Value="Stretch" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
</DataGrid.Resources>
<!--根据状态码不同的行显示不同的颜色(背景/前景)-->
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter Property="Background" Value="Transparent" />
<Setter Property="Foreground" Value="White" />
<Style.Triggers>
<DataTrigger Binding="{Binding State}" Value="2">
<Setter Property="Background" Value="Transparent" />
<Setter Property="Foreground" Value="Yellow" />
</DataTrigger>
<DataTrigger Binding="{Binding State}" Value="3">
<Setter Property="Background" Value="Red" />
<Setter Property="Foreground" Value="White" />
</DataTrigger>
<DataTrigger Binding="{Binding State}" Value="4">
<Setter Property="Background" Value="LimeGreen" />
<Setter Property="Foreground" Value="White" />
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Time}" Header="时间" Width="100" />
<DataGridTextColumn Binding="{Binding Date}" Header="日期" Width="100" />
<DataGridTextColumn Binding="{Binding Description}" Header="事件" Width="*" />
</DataGrid.Columns>
</DataGrid>
-
效果
-
测试