很多时候在显示列表数据时,我们需要交替改变条目的样式例如背景色、边框、前景色...等等以达到更好的视觉效果,下面将给你提供一种较为“规范”的实现思路。
我们将采用WPF内置的两大专用属性ItemsControl.AlternationCount 属性和 ItemsControl.AlternationIndex 附加属性来完成交替条目的样式改变,首先我们来了解下这两个属性:
ItemsControl.AlternationCount :ItemsControl的交替项容器数。
ItemsControl.AlternationIndex: 条目项所在项容器中时被赋予的用于表示交替项位置的索引标志。
下面为AlternationCount 值为2时的示例图。
项目的位置。 | ItemsControl.AlternationIndex |
---|---|
1 | 0 |
2 | 1 |
3 | 0 |
4 | 1 |
5 | 0 |
6 | 1 |
7 | 0 |
项目的位置。 | ItemsControl.AlternationIndex |
---|---|
1 | 0 |
2 | 1 |
3 | 2 |
4 | 0 |
5 | 1 |
6 | 2 |
7 | 0 |
了解了这两个属性,我们基本思路为使用ItemContainerStyle中的Trigger对AlternationIndex进行检查判定来改变相应样式属性。
首先对于ListBox,我们假定交替项容器数为3,条目样式为变背景色为Red、Yellow、Blue三种颜色交替。
<Grid>
<ListBox AlternationCount="3">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Background" Value="Red"/>
<Style.Triggers>
<Trigger Property="ItemsControl.AlternationIndex" Value="1">
<Setter Property="Background" Value="Yellow"/>
</Trigger>
<Trigger Property="ItemsControl.AlternationIndex" Value="2">
<Setter Property="Background" Value="Blue"/>
</Trigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
<TextBlock Text="Tom"/>
<TextBlock Text="Lily"/>
<TextBlock Text="Jack"/>
<TextBlock Text="Tony"/>
<TextBlock Text="Lilice"/>
<TextBlock Text="July"/>
<TextBlock Text="Julie"/>
<TextBlock Text="Bob"/>
<TextBlock Text="Anna"/>
<TextBlock Text="Eva"/>
<TextBlock Text="Frando"/>
<TextBlock Text="Jerry"/>
</ListBox>
</Grid>
对于DataGrid同理,我们只需要对DataGrid.RowStyle应用Trigger检查条目ItemsControl.AlternationIndex 附加属性应用样式。
另外对于DataGrid来说如果仅需两行背景色交替显示,仅设置RowBackground和AlternatingRowBackground即可实现。