ItemsControl WPF的不同数据模板 [英] Different DataTemplates for ItemsControl WPF

查看:60
本文介绍了ItemsControl WPF的不同数据模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在XAML中将ItemsControl定义为:

I have defined an ItemsControl in XAML as:

<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中项目的索引.有什么想法可能会出错吗?

The idea being that I can set different templates based on the current alternation index of the ItemsControl. Whilst this works and gives me the different data templates, I also want the content of the Button to show its alternation index, i.e., the index of the item in MyCollection. Any ideas where I may be going wrong?

推荐答案

尝试

<Button Content="{Binding RelativeSource={RelativeSource AncestorType=ContentPresenter},
                          Path=(ItemsControl.AlternationIndex)}"

ItemsControl.AlternationIndex相同,而不是Button(在您的示例中)居住在ItemContainer(这是ContentPresenter)上.

as ItemsControl.AlternationIndex lives on ItemContainer (which is a ContentPresenter) not Button (in your example).

这篇关于ItemsControl WPF的不同数据模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆