2023-8-1 WPF的ItemsControl容器(DataGrid,ListBox,ListView等)可以实现的隔行样式修改

发布时间 2023-08-01 15:42:30作者: 月长生

实现的隔行样式修改

【作者】长生
微软官方文档详细介绍

实现方式

如果需要让你的wpf表格或者间隔样式实现下列效果可以使用AlternationCount
image
首先添加一个DataGrid,并使用AlternatingRowBackground设置奇数行的背景色为紫色

<DataGrid AlternatingRowBackground="Purple"></DataGrid>

然后在DataGrid里设置RowStyle的具体样式

<DataGrid>
	<DataGrid.RowStyle>
		<Style TargetType="DataGridRow">
		<Setter Property="Background" Value="LightGray"/>//设置复数行样式
		<Style.Triggers>
			<Trigger Property="ItemsControl.AlternationCount" Value="1">
				<Setter Property="Background" Value="Purple"/>
			</Trigger>//这一块是三行样式的设计,可以参考下文
		</Style.Triggers>
		</Style>
	</DataGrid.RowStyle>
</DataGrid>

三行不同颜色的设计

<Grid>
  <Grid.Resources>
    <Style x:Key="alternatingWithTriggers" TargetType="{x:Type ListBoxItem}">
      <Setter Property="Background" Value="Blue"/>//第一行
      <Setter Property="Foreground" Value="White"/>
      <Style.Triggers>
        <Trigger Property="ListBox.AlternationIndex" Value="1">//第二行
          <Setter Property="Background" Value="CornflowerBlue"/>
          <Setter Property="Foreground" Value="Black"/>
        </Trigger>
        <Trigger Property="ListBox.AlternationIndex" Value="2">//第三行
          <Setter Property="Background" Value="LightBlue"/>
          <Setter Property="Foreground" Value="Navy"/>
        </Trigger>
      </Style.Triggers>
    </Style>
  </Grid.Resources>
  <ListBox AlternationCount="3" ItemsSource="{StaticResource data}" 
           ItemContainerStyle="{StaticResource alternatingWithTriggers}">
  </ListBox>
</Grid>

结尾

感谢您的阅读,如果有收获麻烦点个关注!⭐
其他平台
公众号:【长生小殿】
B站:【月长生殿主】