考虑以下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,正如预期的那样。但是,我需要更深层次的AlternationIndex,在第二个ItemsControl中。因此,我不能使用TemplatedParent,并认为我可以用AncestorLevel找到祖先。但是,第二个TextBlock中的两个ItemsControl节点都显示"0“。
我错过了什么?如何从第二个ItemsControl中锁定第一个ItemsControl?
发布于 2016-03-22 10:05:08
AlternationIndex将不是在ItemsControl上,而是在它的每个子程序上。使用DataTemplate,您的ItemsControl将把每个孩子存储在一个有AlternationIndex的ContentPresenter中。您需要修改的内容:
<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)}"/>https://stackoverflow.com/questions/36151090
复制相似问题