问题描述
我在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的不同数据模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!