在wpf中使用DataGrid 虽然方便,但是其默认样式往往很难满足需求,而修改模板往往由比较麻烦,很多时候我们会用ListBox或ListView +DataTemplate 来实现同样效果,但为了有些时候需要应用,这里记录一下一些基本属性设置方法,以免忘记。
code
<Window x:Class="WpfApp7.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp7"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800" Background="Black">
<Window.Resources>
<!--这里模板样式设置在DataGridColumnHeader上,而非DataGridHeader-->
<Style TargetType="DataGridColumnHeader">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="DataGridColumnHeader">
<Grid>
<Border Background="Transparent" BorderBrush="White" BorderThickness="1">
<ContentPresenter Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="DataGridRow">
<!--这里设置行输入背景色为透明色,默认为白色-->
<Setter Property="Background" Value="Transparent" />
</Style>
</Window.Resources>
<Grid>
<!--这里的RowHeaderWidth 是表格最左侧渐冻列,设为0 则没有,默认状态下大概为5,所以如果不设置,而我们又在表头应用了样式,会出现列线和表头列线错位。另外需要设置AutoGenerateColumns为false,否则会自动生成以字段命名的列.CanUserAddRows 增加行-->
<DataGrid RowHeaderWidth="20" ItemsSource="{Binding }" AutoGenerateColumns="False" CanUserAddRows="False" Background="Transparent" Foreground="White"
VerticalGridLinesBrush="White" GridLinesVisibility="Vertical">
<DataGrid.Columns>
<DataGridTextColumn Header="Id" Binding="{Binding Id}" Width="*"/>
<DataGridTextColumn Header="Name" Binding="{Binding Name}" Width="*"/>
<DataGridTextColumn Header="Age" Binding="{Binding Age}" Width="*"/>
<DataGridTextColumn Header="Address" Binding="{Binding Address}" Width="*"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
标签:code,样式,DataGrid,设置,WPF,ListView
From: https://www.cnblogs.com/sundh1981/p/18244491