WPF DataGrid交错行颜色
代码如下
<!-- AutoGenerateColumns="False"可以避免出现重复列 -->
<!-- CanUserAddRows="False"去除最后一行空白行 -->
<DataGrid
x:Name="datagrid"
AlternationCount="2"
AutoGenerateColumns="False"
CanUserAddRows="False">
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Style.Triggers>
<!-- 隔行换色 -->
<Trigger Property="AlternationIndex" Value="0">
<Setter Property="Background" Value="Yellow" />
</Trigger>
<Trigger Property="AlternationIndex" Value="1">
<Setter Property="Background" Value="Blue" />
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Name}" Header="姓名" />
<DataGridTextColumn Binding="{Binding Age}" Header="年龄" />
<DataGridTextColumn Binding="{Binding Address}" Header="地址" />
</DataGrid.Columns>
</DataGrid>
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
List<Person> list = new List<Person>
{
new Person { Name = "张三", Age = 22, Address = "11" },
new Person { Name = "李四", Age = 23, Address = "22" },
new Person { Name = "王五", Age = 24, Address = "33" }
};
datagrid.ItemsSource = list;
}
}
public class Person
{
public string Name { get; set; } = "";
public int Age { get; set; } = 0;
public string Address { get; set; } = "";
}
结果如下: