【问题标题】:Binding ZIndex from DataTemplate从 DataTemplate 绑定 ZIndex
【发布时间】:2012-07-01 02:42:12
【问题描述】:

我有一个基本上是这样设置的视图:

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

这里使用的DataTemplate可以简化为:

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

我现在希望 ZIndex 绑定到单个项目的 Z 属性。当我调试代码时,我还可以看到,Z 属性 getter 在我期望的时候被访问(例如,每当我为它引发 propertychanged 事件时)所以我假设绑定正常工作。

但是,ZIndex 没有按预期工作。绑定到值对实际显示的 Z 顺序没有影响。这段代码我哪里出错了?

【问题讨论】:

    标签: c# wpf xaml binding datatemplate


    【解决方案1】:

    DataTemplate 的内容被包裹在ContentPresenter 中,因此DataTemplate 中的Canvas 不是ItemsPanel Grid 的直接子代。这就是 ZIndex 属性不做任何事情的原因。

    ZIndex Binding 移动到ItemContainerStyle,它应该可以工作。

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

    【讨论】:

      猜你喜欢
      • 2023-04-05
      • 1970-01-01
      • 2013-05-29
      • 2016-03-23
      • 2011-07-21
      • 2011-12-09
      • 1970-01-01
      • 1970-01-01
      • 2022-10-24
      相关资源
      最近更新 更多