C# 从DataTemplate设置ItemsControl中项目的ZIndex

C# 从DataTemplate设置ItemsControl中项目的ZIndex,c#,wpf,z-index,C#,Wpf,Z Index,我在wpf中有以下XAML <Canvas> <ItemsControl ItemsSource="{Binding CompositeCollection}"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <Canvas /> </Ite

我在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中画布的直接子元素。因此设置如下

<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>

...

ItemTemplate中的元素不会成为ItemsPanelTemplate中画布的直接子元素。因此设置如下

<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>

...

Panel.ZIndex=xyz
不工作?@Lennart我该把它放在哪里?这回答了你的问题吗
Panel.ZIndex=xyz
不工作?@Lennart我该把它放在哪里?这回答了你的问题吗?