WPF AlternationIndex to control the visibility of a ControlTemplate

I am using a ControlTemplate for my ListBoxItems for this ListBox. The ControlTemplate is style-defined and contains a rectangle whose visibility should be switched based on AlternationIndex. Although I can see how to use AlternationIndex to directly control the ListBoxItem background, I'm not sure how to use a trigger to refer to a named item in my control template. Any input is evaluated:

XAML Excerpt:

<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">
...

I tried the following, but to no avail. The correct XAML syntax evades me:

<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>

...

+3
source share
1 answer

, 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>
+3

All Articles