我正在为给定ListBox的ListBoxItems使用ControlTemplate。 ControlTemplate在样式中定义,并包含一个矩形,该矩形的可见性需要根据AlternateIndex进行切换。尽管我看到了如何使用AlternateIndex直接控制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>


...

最佳答案

也许您忘记设置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>

关于wpf - WPF AlternateIndex用于控制ControlTemplate项的可见性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5852416/

10-12 20:47