从数据模板设置ItemsControl中项目的ZIndex



我在wpf 中有以下XAML

<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可能包含的两种不同类型,本质上我有两个不同的数据模板。然后根据类型绘制形状1或形状2。

我需要shape1的zindex高于shape2,所以我需要从dataTemplate设置zindex。

我该怎么做?

ItemTemplate中的元素不会成为ItemsPanelTemplate中Canvas的直接子元素。因此设置了类似的内容

<DataTemplate DataType="{x:Type Type1}">
<Shape1 Panel.ZIndex="1"/>
</DataTemplate>

不会有任何影响。

相反,您必须声明ItemContainerStyle:

<ItemsControl ...>
...
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<Setter Property="Panel.ZIndex" Value="{Binding ViewModelItemZIndex}"/>
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>

最新更新