从 DataTemplate 设置 ItemsControl 中项目的 ZIndex

Set ZIndex of items in ItemsControl From DataTemplate

我在 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 可能包含的两种不同类型。然后根据类型绘制 Shape1 或 Shape2。

我需要 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>