考虑以下 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 的祖先。但是,第二个 ItemsControl 中的两个 TextBlock 节点都显示“0”。
我错过了什么?如何从第二个 ItemsControl 中定位第一个 ItemsControl?