ListBox和DataGrid交替条目样式

    很多时候在显示列表数据时,我们需要交替改变条目的样式例如背景色、边框、前景色...等等以达到更好的视觉效果,下面将给你提供一种较为“规范”的实现思路。

    我们将采用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

下面为AlternationCount 值为3时的示例图。

项目的位置。

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即可实现。


  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值