绑定到ItemsControl中ItemsControl的AlternationIndex

时间:2016-03-22 09:52:12

标签: c# wpf xaml binding relativesource

考虑以下XAML

<ItemsControl ItemsSource="{Binding Path=MyItems, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" AlternationCount="999" >
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="{Binding Path=(ItemsControl.AlternationIndex), 
                                        RelativeSource={RelativeSource TemplatedParent}, 
                                        FallbackValue=FAIL, 
                                        StringFormat={}Index is {0}}" />
                <ItemsControl ItemsSource="{Binding Path=MySubItems, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}">
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <StackPanel>
                                <TextBlock Text="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}, AncestorLevel=1}, Path=(ItemsControl.AlternationIndex)}"/>
                                <TextBlock Text="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}, AncestorLevel=2}, Path=(ItemsControl.AlternationIndex)}"/>
                            </StackPanel>
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>
            </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

有三个TextBlock节点。第一个TextBlock是第一个ItemsControl的直接子节点,并按预期显示AlternationIndex。但是,在第二个ItemsControl中,我需要更深层次的AlternationIndex。因此,我无法使用TemplatedParent,并认为我可以找到具有AncestorLevel的Ancestor。但是,第二个ItemsControl中的两个TextBlock节点都显示&#34; 0&#34;。

我错过了什么?如何从第二个ItemsControl中定位第一个ItemsControl?

1 个答案:

答案 0 :(得分:4)

AlternationIndex不会在ItemsControl上,而是在每个子节点上。使用DataTemplate,您的ItemsControl会将每个子项存储在ContentPresenter中,该ContentPresenter将具有AlternationIndex。您需要修改的内容:

<TextBlock Text="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContentPresenter}, AncestorLevel=2}, Path=(ItemsControl.AlternationIndex)}"/>
<TextBlock Text="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContentPresenter}, AncestorLevel=2}, Path=(ItemsControl.AlternationIndex)}"/>
相关问题