ItemsControl WPF

时间:2015-06-04 18:03:19

标签: wpf itemscontrol

我已在XAML中将ItemsControl定义为:

<ItemsControl ItemsSource="{Binding MyCollection}"
              AlternationCount="{Binding RelativeSource={RelativeSource Self}, Path=Items.Count}">

        <ItemsControl.Resources>
            <DataTemplate x:Key="TemplateOne">
                <Button Content="{Binding RelativeSource={RelativeSource Self}, Path=(ItemsControl.AlternationIndex)}" Style="{StaticResource StyleOne}"/>
            </DataTemplate>
            <DataTemplate x:Key="TemplateTwo">
                <Button Content="{Binding RelativeSource={RelativeSource Self}, Path=(ItemsControl.AlternationIndex)}" Style="{StaticResource StyleTwo}"/>
            </DataTemplate>
        </ItemsControl.Resources>

        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Horizontal"/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>

        <ItemsControl.ItemContainerStyle>
            <Style TargetType="ContentPresenter">
                <Style.Triggers>
                    <Trigger Property="ItemsControl.AlternationIndex" Value="0">
                        <Setter Property="ContentTemplate" Value="{StaticResource TemplateOne}"></Setter>
                    </Trigger>
                    <Trigger Property="ItemsControl.AlternationIndex" Value="1">
                        <Setter Property="ContentTemplate" Value="{StaticResource TemplateTwo}"></Setter>
                    </Trigger>
                </Style.Triggers>                    
            </Style>
        </ItemsControl.ItemContainerStyle>           

    </ItemsControl>

我的想法是,我可以根据ItemsControl的当前交替索引设置不同的模板。虽然这有效并且给了我不同的数据模板,但我还希望Button的内容显示其交替索引,即MyCollection中项目的索引。我可能会出错的任何想法?

2 个答案:

答案 0 :(得分:1)

尝试

m[order(unlist(m), decreasing=TRUE)]

<Button Content="{Binding RelativeSource={RelativeSource AncestorType=ContentPresenter}, Path=(ItemsControl.AlternationIndex)}" 位于ItemsControl.AlternationIndexItemContainer)而不是ContentPresenter(在您的示例中)。

答案 1 :(得分:0)

您还没有获得所有商品的替代款式。你只有两个。我将ItemsControl Count设置为2。 所以这是你的ItemsControl(它包括@LPL&#39的解决方案)

    <ItemsControl ItemsSource="{Binding MyCollection}"
          AlternationCount="2">

        <ItemsControl.Resources>
            <DataTemplate x:Key="TemplateOne">
                <Button Content="{Binding RelativeSource={RelativeSource AncestorType=ContentPresenter}, Path=(ItemsControl.AlternationIndex)}" Style="{StaticResource StyleOne}"/>
            </DataTemplate>
            <DataTemplate x:Key="TemplateTwo">
                <Button Content="{Binding RelativeSource={RelativeSource AncestorType=ContentPresenter}, Path=(ItemsControl.AlternationIndex)}" Style="{StaticResource StyleTwo}"/>
            </DataTemplate>
        </ItemsControl.Resources>

ItemsControl AlternationCount on MSDN

相关问题