《学习笔记》WPF-DataGrid(数据表格)美化
我们不多哔哔先上图:
数据表格使用背景:
当我们在做二次开发发现我我们的表格无法向WEB的表格一样好看,这时我们就需要对数据表格进行美化和重构
表格美化思维引导:
WPF数据表格是由表头和表体(内容)组成那么我们就要对这两部分单独美化
表头美化代码:
1 <Style x:Key="DataGridStyle" TargetType="DataGrid"> 2 <Setter Property="ColumnHeaderStyle" Value="{DynamicResource ColumnHeaderStyle}"></Setter> 3 <Setter Property="CellStyle" Value="{DynamicResource CellStyle}"></Setter> 4 <Setter Property="RowStyle" Value="{DynamicResource RowStyle}"></Setter> 5 <Setter Property="Background" Value="White"></Setter> 6 <Setter Property="EnableRowVirtualization" Value="False"></Setter> 7 <Setter Property="GridLinesVisibility" Value="None"></Setter> 8 <Setter Property="CanUserAddRows" Value="False"></Setter><!--禁止在尾行手动添加数据--> 9 <Setter Property="AutoGenerateColumns" Value="False"></Setter> 10 <Setter Property="IsEnabled" Value="True"></Setter> 11 </Style> 12 <Style x:Key="ColumnHeaderStyle" TargetType="DataGridColumnHeader"> 13 <Setter Property="Height" Value="35"></Setter> 14 <Setter Property="Background" Value="#F2F2F2"></Setter> 15 <Setter Property="BorderThickness" Value="1"></Setter> 16 <Setter Property="BorderBrush" Value="#CBCBCB"></Setter> 17 <Setter Property="VerticalContentAlignment" Value="Center"></Setter><!--水平居中--> 18 <Setter Property="HorizontalContentAlignment" Value="Center"></Setter><!--垂直居中-->
19 </Style>
美化表体每行样式
1 <Style x:Key="RowStyle" TargetType="DataGridRow"> 2 <Setter Property="Cursor" Value="Hand"></Setter> 3 <Style.Triggers> 4 <Trigger Property="IsMouseOver" Value="true"> 5 <Setter Property="Background" Value="#F2F2F2"/> 6 </Trigger> 7 <Trigger Property="IsSelected" Value="True"> 8 <Setter Property="Background" Value="#CBCBCB" /> 9 </Trigger> 10 </Style.Triggers> 11 </Style>
美化表体单元格内容样式
1 <Style x:Key="CellStyle" TargetType="DataGridCell"> 2 <Setter Property="Height" Value="35"></Setter> 3 <Setter Property="FontSize" Value="13"></Setter> 4 <Setter Property="Template"> 5 <Setter.Value> 6 <ControlTemplate TargetType="DataGridCell"> 7 <Border x:Name="Bg" Background="Transparent" BorderThickness="1" UseLayoutRounding="True" BorderBrush="#FFCBCBCB"> 8 <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" /> 9 </Border> 10 </ControlTemplate> 11 12 </Setter.Value> 13 </Setter> 14 <Style.Triggers> 15 <Trigger Property="IsSelected" Value="True"> 16 <Setter Property="Background" Value="#CBCBCB" /> 17 <Setter Property="Foreground" Value="#000000" /> 18 </Trigger> 19 </Style.Triggers> 20 </Style>
注意:鼠标点击当前行时需要覆盖单元格颜色