C# 绑定到ItemsControl中ItemsControl的AlternationalIndex
考虑以下XAMLC# 绑定到ItemsControl中ItemsControl的AlternationalIndex,c#,wpf,xaml,binding,relativesource,C#,Wpf,Xaml,Binding,Relativesource,考虑以下XAML <ItemsControl ItemsSource="{Binding Path=MyItems, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" AlternationCount="999" > <ItemsControl.ItemTemplate> <DataTemplate> <StackPanel>
<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节点。第一个文本块是第一个ItemsControl的直接子级,并按预期显示AlternationIndex。但是,我需要在第二个ItemsControl中更深一层的AlternationIndex。因此,我不能使用TemplatedParent,我认为我可以找到具有AncestorLevel的祖先。但是,第二个ItemsControl中的两个TextBlock节点都显示“0”
我错过了什么?如何从第二个ItemsControl中确定第一个ItemsControl的目标?替代索引将不在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)}"/>
替代索引将不在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)}"/>