在带有 Canvas ItemsPanel 的 ListBox 的上下文中,我需要为多个 DataTemplates 中的每个控件访问 Cavas.ZIndex (列表显示几种对象类型)。使用一个是不够的
<ListBox.ItemContainerStyle>
<Setter Property="Canvas.ZIndex" ..... />
因为有几个数据模板,每个模板都有几个控件,我想控制每个控件的绝对 zindex。这甚至可能吗?
在带有 Canvas ItemsPanel 的 ListBox 的上下文中,我需要为多个 DataTemplates 中的每个控件访问 Cavas.ZIndex (列表显示几种对象类型)。使用一个是不够的
<ListBox.ItemContainerStyle>
<Setter Property="Canvas.ZIndex" ..... />
因为有几个数据模板,每个模板都有几个控件,我想控制每个控件的绝对 zindex。这甚至可能吗?
据我所知,这是不可能的
原因是当 ListBox 呈现时,它呈现如下(假设您指的是与您在其他问题中的代码相同的代码):
<Canvas>
<ListBoxItem>
<ContentPresenter>
<Grid>
<TextBlock />
<Line />
</Grid>
</ContentPresenter>
</ListBoxItem>
<ListBoxItem>
<ContentPresenter>
<Grid>
<TextBlock />
<Line />
</Grid>
</ContentPresenter>
</ListBoxItem>
<ListBoxItem>
<ContentPresenter>
<Grid>
<TextBlock />
<Line />
</Grid>
</ContentPresenter>
</ListBoxItem>
...
</Canvas>
如您所见,每个 ListBoxItem 都呈现为一组嵌套控件。您不能将所有 TextBlocks 绘制在所有 Lines 之上,因为它们并不都共享相同的父级,并且 ZIndex 用于对同一父级容器中的项目进行排序。
一种解决方法是使用两个相互叠加的独立 ItemsControl。因此,您的所有线条都将绘制在底部 ItemsControl 上,而所有 TextBlock 将绘制在顶部 ItemsControl 上。
<Grid>
<ItemsControl ItemsSource="{Binding MyData}"
ItemTemplate="{DynamicResource MyLineTemplate}" />
<ItemsControl ItemsSource="{Binding MyData}"
ItemTemplate="{DynamicResource MyTextBlockTemplate}" />
</Grid>