从 DataTemplate 设置 ItemsControl 中项目的 ZIndex [英] Set ZIndex of items in ItemsControl From DataTemplate
问题描述
我在 wpf 中有以下 XAML
I have the following XAML in wpf
<Canvas>
<ItemsControl ItemsSource="{Binding CompositeCollection}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.Resources>
<DataTemplate DataType="{x:Type Type1}">
<Shape1/>
</DataTemplate>
<DataTemplate DataType="{x:Type type2}">
<Shape2/>
</DataTemplate>
</ItemsControl.Resources>
</ItemsControl>
</Canvas>
所以基本上我有两个不同的数据模板,用于我的 System.Windows.Data.CompositeCollection
可能包含的两种不同类型.然后根据类型绘制 Shape1 或 Shape2.
So essentially I have two different data templates for the two different types my System.Windows.Data.CompositeCollection
may contain. Either Shape1 or Shape2 is then drawn based on the type.
我需要 shape1 的 zindex 高于 shape2,所以我需要从 dataTemplate 设置 zindex.
I need the zindex for shape1 to be higher than shape2, so I need to set the zindex from the dataTemplate.
我该怎么做?
推荐答案
ItemTemplate 中的元素不会成为 ItemsPanelTemplate 中 Canvas 的直接子元素.因此设置类似
The elements in the ItemTemplate will not become direct child elements of the Canvas in the ItemsPanelTemplate. Hence setting something like
<DataTemplate DataType="{x:Type Type1}">
<Shape1 Panel.ZIndex="1"/>
</DataTemplate>
不会有任何影响.
您必须声明一个 ItemContainerStyle:
You would instead have to declare an ItemContainerStyle:
<ItemsControl ...>
...
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<Setter Property="Panel.ZIndex" Value="{Binding ViewModelItemZIndex}"/>
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
这篇关于从 DataTemplate 设置 ItemsControl 中项目的 ZIndex的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!