在ItemsControl的数据模板中设置Canvas属性

86

我正在尝试将数据绑定到这个ItemsControl

<ItemsControl ItemsSource="{Binding Path=Nodes, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

通过使用这个 DataTemplate,我试图正确地在 Canvas 上单独定位我的 Node 元素:

<DataTemplate DataType="{x:Type Model:EndNode}">
    <Controls:EndNodeControl Canvas.Left="{Binding Path=XPos}" Canvas.Top="{Binding Path=YPos}" />
</DataTemplate>

然而,它并没有按预期工作。所有节点元素都在相同的位置上重叠绘制。有什么建议可以实现这一点吗?

1个回答

152

所附加的属性仅适用于Canvas的直接子元素。 ItemsControl会将ContentPresenter控件放置为其直接子代,因此您可能还需要为此添加样式:

<ItemsControl ItemsSource="{Binding Path=Nodes}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemContainerStyle>
        <Style TargetType="ContentPresenter">
            <Setter Property="Canvas.Left" Value="{Binding Path=XPos}" />
            <Setter Property="Canvas.Top" Value="{Binding Path=YPos}" />
        </Style>
    </ItemsControl.ItemContainerStyle>
</ItemsControl>

11
我也喜欢那些“啊哈”时刻;并不是所有的事情都糟糕。也许你的问题有一天能帮助其他人。你永远不知道! - Arcturus
1
@skb 我也有同样的问题,是否有关于这个的Silverlight解决方案? - themaestro
5
如果我的X和Y位置应该在ItemsSource中的一个对象内,该怎么办?我的ItemsSource中有一个Point对象。 - El Mac
1
我找到了一个针对Metro/UWP应用的解决方法 - http://stackoverflow.com/a/37821355/3431319 - Arctic Vowel
1
即使过去了14年。;) - Thomas Mutzl
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接