带有两个数据模板和交替索引触发器的列表框内容控件,xaml

Listbox contentcontrol with two data templates and triggers on alternationindex, xaml

我有一个 ListBox 并且我希望它有 2 个完全不同的数据模板样式,具体取决于交替索引。我看过很多关于如何根据索引更改背景颜色但不更改每个索引的样式的教程。这是我目前所拥有的。

定义的模板:

<UserControl.Resources>
    <DataTemplate x:Key="ItemLeft" >
        <Border Background="Blue" Height="10">
            <!-- Define Left Style -->

        </Border>
    </DataTemplate>
    <DataTemplate x:Key="ItemRight">
        <Border Background="Red" Height="10">
            <!-- Define Right Style -->

        </Border>
    </DataTemplate>
</UserControl.Resources>

我删除了数据模板代码以使其更易于阅读。它不仅仅是边框颜色。

列表框:

        <ListBox Name="StatusListBox" AlternationCount="2">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <ContentControl Content="{Binding}">
                        <ContentControl.Style>
                            <Style TargetType="{x:Type ContentControl}">
                                <Setter Property="ContentTemplate" Value="{StaticResource ItemLeft}"/>
                                <Style.Triggers>
                                    <DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ContentPresenter}}, Path=(ListBox.AlternationIndex)}" Value="1">
                                        <Setter Property="ContentTemplate" Value="{StaticResource ItemRight}"/>
                                    </DataTrigger>
                                </Style.Triggers>
                            </Style>
                        </ContentControl.Style>
                    </ContentControl>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

此代码未正确设置内容控件。我要么做错了,要么又错过了一步。我是使用 WPF 的新手,我发现它的大部分内容都非常直观,但我在这里迷路了。我想尝试将其包含在 XAML 代码中。

谢谢

您可以直接设置 ItemContainerStyle 而不是在 ItemTemplate 中设置 ContentPresenter 的样式。对于 AlternationIndex:

,样式将具有 Trigger 而不是 DataTrigger
<ListBox AlternationCount="2">
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="ContentTemplate" Value="{StaticResource ItemLeft}"/>
            <Style.Triggers>
                <Trigger Property="ItemsControl.AlternationIndex" Value="1">
                    <Setter Property="ContentTemplate"
                            Value="{StaticResource ItemRight}"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>