代码之家  ›  专栏  ›  技术社区  ›  Yair Halberstadt

从数据模板设置itemscontrol中项的zindex

  •  0
  • Yair Halberstadt  · 技术社区  · 7 年前

    我在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。

    我该怎么做?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Clemens    7 年前

    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>