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