WPF AlternationIndex控制ControlTemplate项的可见性

时间:2011-05-02 00:20:21

标签: wpf xaml

我为给定的ListBox使用ControlTemplate作为我的ListBoxItems。 ControlTemplate在Style中定义,并包含一个Rectangle,其Visibility需要根据AlternationIndex进行切换。虽然我看到如何使用AlternationIndex直接控制ListBoxItem的背景,但我不确定如何使用触发器来引用我的控件模板中的命名项。任何意见都表示赞赏:

XAML摘录:

<Style x:Key="ListBoxItemStyle" TargetType="{x:Type ListBoxItem}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ListBoxItem}">
                <Grid Height="84" Width="700">
                    <!--
                    TURN ME ON FOR EVERY EVEN NUMBERED LIST ITEM
                    -->
                    <Rectangle x:Name="_listItemBg" Width="700" Height="83" Opacity="0.12">
...

我尝试过以下内容,但无济于事。正确的XAML语法避开了我:

<ControlTemplate.Triggers>
    <Trigger Property="ItemsControl.AlternationIndex" Value="0">
        <Setter Property="Rectangle.Visibility" TargetName="_listItemBg" Value="Hidden" />
    </Trigger>
    <Trigger Property="ItemsControl.AlternationIndex" Value="1">
        <Setter Property="Rectangle.Visibility" TargetName="_listItemBg" Value="Visible" />
    </Trigger>

...

1 个答案:

答案 0 :(得分:3)

也许您忘了设置AlternationCount?在任何情况下,这里都是一个基于您的代码的小型独立工作样本:

<Grid>
    <Grid.Resources>
        <PointCollection x:Key="sampleData">
            <Point>1,2</Point>
            <Point>3,4</Point>
            <Point>5,6</Point>
        </PointCollection>
    </Grid.Resources>
    <ListBox ItemsSource="{StaticResource sampleData}" AlternationCount="2">
        <ListBox.ItemContainerStyle>
            <Style TargetType="ListBoxItem">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type ListBoxItem}">
                            <Grid Height="84" Width="700">
                                <Rectangle x:Name="_listItemBg" Width="700" Height="83" Fill="Red" Opacity="0.12"/>
                            </Grid>
                            <ControlTemplate.Triggers>
                                <Trigger Property="ItemsControl.AlternationIndex" Value="0">
                                    <Setter Property="Rectangle.Visibility" TargetName="_listItemBg" Value="Hidden" />
                                </Trigger>
                                <Trigger Property="ItemsControl.AlternationIndex" Value="1">
                                    <Setter Property="Rectangle.Visibility" TargetName="_listItemBg" Value="Visible" />
                                </Trigger>
                            </ControlTemplate.Triggers>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </ListBox.ItemContainerStyle>
    </ListBox>
</Grid>