Binding ZIndex from DataTemplate

你离开我真会死。 提交于 2020-08-25 03:51:45

问题


I have a View that is basically setup like this:

<Grid>
<ViewBox>
    <Grid>
        <ItemsControl ItemsSource="{Binding MyItems}"
                      ItemTemplate="{Binding Source={StaticResource MyItemsDataTemplate}}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <Grid />
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
        </ItemsControl>
    </Grid>
</ViewBox>
</Grid>

The DataTemplate used here can be reduced to this:

<DataTemplate x:Key="AreaItemDisplayDataTemplate">
<Canvas Grid.ZIndex={Binding Z}>
    <Grid>
        // an shape is displayed here...
    </Grid>
</Canvas>

I would now expect the ZIndex to be bound to the Z property of the individual items. When i debug the code, i can also see, that the Z property getter is accessed when i would expect it (whenever i raise the propertychanged event for it, eg) so i assume the binding to work correctly.

However, the ZIndex is not working as expected. The binding to the value has no effect on the actual displayed Z Order. Where am i going wrong with this code?


回答1:


The content of the DataTemplate gets wrapped in a ContentPresenter so the Canvas in the DataTemplate isn't a direct child of the ItemsPanel Grid. That is the reason the ZIndex property doesn't do anything.

Move the ZIndex Binding to the ItemContainerStyle and it should work.

<ItemsControl ItemsSource="{Binding MyItems}" 
              ItemTemplate="{Binding Source={StaticResource MyItemsDataTemplate}}"> 
    <ItemsControl.ItemsPanel> 
        <ItemsPanelTemplate> 
            <Grid /> 
        </ItemsPanelTemplate> 
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemContainerStyle>
        <Style TargetType="ContentPresenter">
            <Setter Property="Grid.ZIndex" Value="{Binding Z}"/>
        </Style>
    </ItemsControl.ItemContainerStyle>
</ItemsControl> 


来源:https://stackoverflow.com/questions/11263946/binding-zindex-from-datatemplate

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