Set ZIndex of items in ItemsControl From DataTemplate

醉酒当歌 提交于 2020-01-16 08:51:28

问题


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>

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.

I need the zindex for shape1 to be higher than shape2, so I need to set the zindex from the dataTemplate.

How would I do this?


回答1:


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>

will have no effect.

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>


来源:https://stackoverflow.com/questions/51306964/set-zindex-of-items-in-itemscontrol-from-datatemplate

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!